• Home
  • About
    • Pywind photo

      Pywind

      This is py blog !

    • Learn More
    • Facebook
    • Instagram
    • Github
    • StackOverflow
    • Youtube
  • Posts
    • All Posts
    • All Tags
  • Projects

C# Object Oriented Programming

28 Aug 2020

Reading time ~14 minutes

Some useful function C#

  • $”” string
int n = 3, m = 5;
string s = "New string";
Console.Write($"This is {s}, {s.ToUpper()} and we can show {n} & {m} or {m * n}");
//This is New string, NEW STRING and we can show 3 & 5 or 15
  • List example
    // Declare list
    var names = new List<string> { "Apple", "Organ", "Banana" };

Some methods in list:

  • List foreach (var index in <List>)
  • List.Count();
  • List.IndexOf("element_find"); return index or -1
  • List.Sort()
  • List.Add() “Add more index”

String

  • Replace
"3ndl3arn".Replace('3', 'e');
//endlearn
"Blackcat".Replace("Black", "White");
//Whitecat
  • s.ToUpper() / s.ToLower()
  • IndexOf
string s = "This is example";
s.IndexOf("is"); // 5
s.IndexOf("not"); // -1
  • StartsWith & EndsWith
string name = "Pywind's blog C#";

name.StartsWith("P"); // true
name.StartsWith("Pywind"); // true

name.EndsWith("blog"); // false

  • Split
string s = "Welcome to my blog";
string[] words = s.Split(' '); //["Welcome", "to", "my", "blog"]
  • Substring
string name = "A string to test !";
// from index a to b
name.substring(0, 4) // A str
name.substring(2, 7) // string

Delegate

Delegate is a data type, used to reference (pointer) to functions(methods) whose parameters and return the type which is declared.

  • When using a delegate, you can assign to it one, many functions (methods) have parameter compatibility, return type, then use it to call the function (like pointer in C ++)
  • event in C# are functions that are called through delegate

    Declare

    public delegate <data_type> name_delegate(params)
    

    Usage

ShowLog log;

Ex:

public delegate string ShowLog(string message)

Nếu có sự tương đồng ta có thể gán chúng thông qua delegate, hoặc truyền thông qua delegate

Ex:

// declare delegate
public delegate string ShowLog(string message)
// some methods
public string ErrorTime(string s) => // some message
public string Warning(string s) => // some warning

// in orther methos we can: 

showLog = ErrorTime;
showLog("Something wants to show");

showLog = Warning;
showLog("WARNING 404");

Gán nhiều method thông qua delegate

Một delegate có thể đưa vào nó nhiều phương thức để một lần gọi thi hành tất cả các phương thức nó chứa:

  • Operator +=: Nối thêm một phương thức vào delegate
  • Operator -=: Loại bỏ 1 phương ở cuối (nếu phương thức đó có trong delegate, tính từ cuối)

Hoặc thông qua lambda expresssion, ta vẫn có thể gán vào delegate

showLog += (x) => $"===>{x}<===";

Cộng nhiều delegate cùng kiểu trả về

// Cộng nhiều Delegate
public static void TestShowLogPlus()
{
    ShowLog showLog1 = (x)=> $"-----{x}-----";
    ShowLog showLog2 = Warning;
    ShowLog showLog3 = Info;

    var all = showLog1 + showLog2 + showLog3 + showLog1;

    all("Xin Chào");
}

Event

An event is a notification sent by an object to signal the occurrence of an action.

  • The class who raises events is called Publisher, and the class who receives the notification is called Subscriber.
  • There can be multiple subscribers of a single event.
  • A publisher raises an event when some action occurred. The subscribers, who are interested in getting a notification when an action occurred, should register with an event and handle it.
Event Publisher & Subscriber

Declare a Event

By two steps:

  • Declare a void delegate
    • Delegate has two parameters, the first is object, and the second is EventArgs which generates the event
  • Declare a variable of that delegate with event keyword

Ex:

//delegate
public delegate void Notify(object obj);
//event 
public event Notify OnFinished;

Func và Action

Func là mẫu delegate có kiểu trả về. Để khai báo biến delegate dùng cú pháp như sau:

Func<param_1, param_2, …, return_type> var_delegate;

Params

Important Point About Params Keyword :

  • It is useful when programmer don’t have any prior knowledge about the number of parameters to be used.
  • Only one Params keyword is allowed and no additional Params will be allowed in function declaration after a params keyword.
  • The length of params will be zero if no arguments will be passed.

params data_type[] name_params

// function using object type params  
public void result(params object[] array)  
{
    for (int i = 0; i < array.Length; i++)  
    {              
        // Display result 
        Console.WriteLine(array[i]);  
    }      
}

obj.results("first", "coding", "10.0");

Dictionary

Dictionary trong C# là một Collections lưu trữ dữ liệu dưới dạng cặp Key - Value.

Trước khi sử dụng, do Dictionary là 1 Generic Collections nên để sử dụng ta cần thêm thư viện System.Collections.Generic bằng câu lệnh:

using System.Collections.Generic;

Khai báo 1 dictionary:

 Dictionary<dtype, dtype> couple = new Dictionary<dtype, dtype>(#capacity);
 
 // Example
Dictionary<int, string> book = new Dictionary<int, string>(5);

// By other dict
/*
 * Khởi tạo 1 Dictionary có kích thước bằng với MyDic2.
 * Sao chép toàn độ phần tử trong MyDic2 vào MyDic3.
 */
Dictionary<string, string> MyDic3 = new Dictionary<string, string>(MyDic2);

Một số method và attributes có sẵn

Attributes Means
Count Số phần tử hiện có trong Dictionary
Keys Trả về danh sách chứa key trong Dictionary
Values Trả về sanh sách chứa value trong Dictionary

Một số methos

Methods Means
Add(TKey Key, TValue Value) Thêm 1 cặp Key - Value
ContainsKey(TKey Key) Kiểm tra Key có tồn tại trong Dictionary
Remove(TKey Key) Xoá đối tượng có Key xuất hiện đầu tiên trong Dictionary
TryGetValue(TKey Key, TValue Value) Kiểm tra Key có tồn tại hay không. Nếu có sẽ trả về true đồng thời trả về giá trị Value tương ứng qua biến Value.Ngược lại trả về false
Clear() Xoá tất cả các phần tử trong Dictionary

Object-Oriented Programming in C#

Create a Class

To create a class, use the class keyword:

class <Name>
{
    <access range><component>;
}

E.g:

class Animal
{
    public double Weight;
    public double Height;

    public void Run()
    {
        Console.WriteLine(" Animal is running. . .");
    }
}

Create an Object

by new operator:

<Name_class> Name_Obj = new Name_class();

Class is the reference data type, is stored on the heap

Fields

Call attributions:

Variables, methods inside a class are called fields, and that you can access them by creating an object of the class and by using the dot syntax (.).

<Name object>.<method>(<reference>);

Encapsulation

To control the visibility of class members (the security level of each individual class and class member).

The meaning of Encapsulation, is to make sure that “sensitive” data is hidden from users. To achieve this, you must:

declare attributes as private provide public get and set methods, through attributes, to access and update the value of a private field

Access specifiers and meaning

Modifier Description
public Unlimited, access anywhere
private Only accessible inside the class
protected Like private and accessible from derived classes
internal access in the same project
protected internal Like internal and accessible from derived classes

Since it doesn’t specify keywords, the class will have internal.

Properties (Get and Set)

  • The query methods should start with the get keyword and be followed by the name of the property
  • The update methods should start with the set keyword followed by the property name.
  • If the property is boolean, the query method name must begin with the keyword is and be followed by the property name.
  • The update method return type void and have 1 parameter passed with the same type as the data type of the property.
  • Syntax:
<data type> <name of property>

    {
        get { return <name of property>; }
        set { <name of property> = value; }

    }

E.g:

private double diemLy;
public double DiemLy
{
get { return diemLy; }
set { diemLy = value; }
}
  • Depending on the needs and security, the programmer can prevent value assignment or prevent data from being obtained by omitting the corresponding keyword.
set
{
    if (value <= 10 && value >=0 )
    {
        phys = value;
    }
}

Automatic Properties (Short Hand)

A way to use short-hand / automatic properties, where you do not have to define the field for the property, and you only have to write get; and set; inside the property.

class Person
{
  private string Name  // property
  { get; set; }
}

Constructor and Destructor

Constructor

A constructor is a special method that is used to initialize objects. The advantage of a constructor, is that it is called when an object of a class is created. It can be used to set initial values for attributes.

Constructor has two types:

  • no arguments
    • initializes default values ​​for attributes inside the class on object initialization
  • arguments
    • When the object is instantiated for this method to be called, we need to pass all the parameters.
    • to initialize values ​​for attributes inside the class during object initialization
// no argument

public Cat()
{
    Weight = 1.5; // Default values
    Height = 10;
}

// has argument

public Cat(int w, int h)
{
    Weight = w;
    Height = h;
}

Destructor

Special methods are called before an object is retrieved.

  • Having the same name as the class name, but to distinguish it from the constructor, we add a “~” sign before the class name.
  • There is no return type.
  • If you do not declare destructor, C # will automatically create a default destructor.
  • There is only 1 destructor in 1 layer.

Static members

Sometimes a programmer wants a certain property to be shared by all objects (to be allocated only one memory area). Since then the concept of static members came into being.

Characteristics:

  • Initialized once only after compiling the program.
  • Can be used for all subjects.
  • Called by class name.
  • Have: static variable, static method, static class, static constructor.

Static variable

<access range> static <data type> <name_variable> = <values>;

E.g:

public static int Count = 0;

Static method

  • Static method is common function of class. Called by class name, no initialize, avoid waste of memory.
  • Support to write utilities function.
<access> static <return type> <name_method>
{
    // purpose inside
}

Static class

  • Can contain static methods, static variables.
<access range> static class <name_class>

{
// attributes
}

Inheritance

  • build a new class from an existing class.
    • A new class is called subclass or derived class.
    • An existing class is called a superclass or a base class.
  • Reuse and easy to upgrade, easy to maintain.

To inherit from a class, use the : symbol.

Syntax:

class <name_subclass> : <superclass>
{

}

E.g:

class Vehicle  // base class (parent)
{
  public string brand = "Ford";  // Vehicle field
  public void honk()             // Vehicle method
  {
    Console.WriteLine("Bruh, Bruh!");
  }
}

class Car : Vehicle  // derived class (child)
{
  public string modelName = "Mustang";  // Car field
}

The sealed Keyword

If you don’t want other classes to inherit from a class, use the sealed keyword:

sealed class Vehicle
{
  ...
}

class Car : Vehicle
{
  ...
}

‘Car’: cannot derive from sealed type ‘Vehicle’

Issues in inheritance

The superclass default constructor is always called every time an object of the subclass is initialized. And called before the subclass constructor. Subclass must have a corresponding constructor and call the superclass constructor method through the keyword base.

Syntax:

public <name_class>(<parameter list of subclass>) : base(<parameter list>)
{
    //content
}
  • parameter list is the parameter list corresponding to the constructor of the superclass.

E.g:

class Animal
    {
        public Animal(double w, double h, int l)
        {
            Weight = w;
            Height = h;
            Legs = l;
        }
    }

class Cat : Animal
    {
        public Cat()
        {
            Weight = 1500;
            Height = 20;
            Leg = 4;
        }
        public Cat(double w, double h, int l) : base(w, h, l)
        {
            //
        }
    }

  • In C # there is support for the new keyword to mark this as a new function and the function inheriting from the superclass will be masked so that the outside cannot be called.

An object of the superclass can refer to the memory of an object belonging to the subclass, but otherwise cannot.

Polymorphism

Polymorphism means “many forms”, and it occurs when we have many classes that are related to each other by inheritance.

Virtual and override

  • Virtual is the keyword used to declare a virtual method (virtual methods are overridden methods).
  • Override is the keyword used to mark the method that overrides the method of the superclass.

Note: {: .notice}

  • Only override virtual or abstract methods.
  • Polymorphism is only shown when the superclass method is overridden.

E.g:

class Animal  // Base class (parent)
{
  public void animalSound()
  {
    Console.WriteLine("The animal makes a sound");
  }
}

class Pig : Animal  // Derived class (child)
{
  public void animalSound()
  {
    Console.WriteLine("The pig says: wee wee");
  }
}

class Dog : Animal  // Derived class (child)
{
  public void animalSound()
  {
    Console.WriteLine("The dog says: bow wow");
  }
}

class Program
{
  static void Main(string[] args)
  {
    Animal myAnimal = new Animal();  // Create a Animal object
    Animal myPig = new Pig();  // Create a Pig object
    Animal myDog = new Dog();  // Create a Dog object

    myAnimal.animalSound();
    myPig.animalSound();
    myDog.animalSound();
  }
}

The output will be:

The animal makes a sound
The animal makes a sound
The animal makes a sound

We need to override the animalSound() method of the superclass (Animal class) and to override it, we need to declare the animalSound() method of the superclass as a virtual method.

class Animal  // Base class (parent)
{
  public virtual void animalSound()
  {
    Console.WriteLine("The animal makes a sound");
  }
}

class Pig : Animal  // Derived class (child)
{
  public override void animalSound()
  {
    Console.WriteLine("The pig says: wee wee");
  }
}

class Dog : Animal  // Derived class (child)
{
  public override void animalSound()
  {
    Console.WriteLine("The dog says: bow wow");
  }
}

Now, output will be:

The animal makes a sound
The pig says: wee wee
The dog says: bow wow

Note: Derived class can override or not

Abstraction

Data abstraction is the process of hiding certain details and showing only essential information to the user. Abstraction can be achieved with either abstract classes or interfaces.

  • Virtual method is a virtual method and has no internal definition.
  • Abstract is the keyword used to declare an abstract class or a pure virtual method.
  • Abstract class is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class)
  • Abstract method: can only be used in an abstract class, and it does not have a body. The body is provided by the derived class (inherited from).

E.g:

abstract class Animal
{
  public abstract void animalSound();
  public void sleep()
  {
    Console.WriteLine("Zzz");
  }
}

From the example above, it is not possible to create an object of the Animal class:

Animal myObj = new Animal();

Warning: Cannot create an instance of the abstract class or interface ‘Animal’

  • When implementing abstract on the superclass. We can override from subclass. The parent class has no inner definition.

Note: When inheriting an abstract class you are required to override all pure virtual methods to ensure program validity.

E.g:

// Abstract class
abstract class Animal
{
  // Abstract method (does not have a body)
  public abstract void animalSound();
  // Regular method
  public void sleep()
  {
    Console.WriteLine("Zzz");
  }
}

// Derived class (inherit from Animal)
class Pig : Animal
{
  public override void animalSound()
  {
    // The body of animalSound() is provided here
    Console.WriteLine("The pig says: wee wee");
  }
}

Note: Interfaces can contain properties and methods, but not fields.

To access the interface methods, the interface must be “implemented” (like inherited) by another class. To implement an interface, use the : symbol (just like inheritance). The body of the interface method is provided by the “implement” class. Note that you do not have to use the override keyword when implementing an interface:

// Interface
interface IAnimal
{
  void animalSound(); // interface method (does not have a body)
}

// Pig "implements" the IAnimal interface
class Pig : IAnimal
{
  public void animalSound()
  {
    // The body of animalSound() is provided here
    Console.WriteLine("The pig says: wee wee");
  }
}

It’s a good way to start with the letter “I” at the beginning of an interface, as it makes easier for yourself and others to remember that it’s an interface and not a class.

Interface methods

Every subclass can override the interface methods in superclass

//In superclass
public class Animal 
{
    public interface
}

Interface vs Abstrac class

  • An class can implement any number of interface class but a subclass only inherated from an abstrac class.
  • An abstrac class can have non-abstrac methods while interface, all methods must to abstrac.
  • An abstract class can declare or use any variables while an interface is not allowed to do so.
  • In an abstract class, all data members or functions are private by default while in an interface all are public, we can’t change them manually.
  • In an abstract class, we need to use abstract keywords to declare abstract methods, while in an interface we don’t need to use that.
  • An abstract class can’t be used for multiple inheritance while the interface can be used as multiple inheritance.
  • An abstract class use constructor while in an interface we don’t have any type of constructor.


projectC#useful Share Tweet +1