Automatic Properties C#

[dropcap]A[/dropcap]utomatic properties used as a shorter way of defining a simple property which just sets and gets the value of a private member variable. Consider the following Code;

public class Point
 {
    private int _x, _y;
    public int X
    {
        get
        {
          return _x;
        }
        set
        {
          _x = value;
        }
    }
    public int Y
    {
        get
        {
          return _y;
        }
        set
        {
          _y = value;
        }
    }
}

The above code simply defining a class with basic properties. Now with the new C# compiler in Visual Studio .NET, we can write a shorter cleaner version using Automatic Properties which automatically generates the private fields with get/set operations :

public class Point
{
    public int X { get; set; }
    public int Y { get; set; }
}

The code above is even more readable and less verbose.
Note that this feature has nothing to do with LINQ. I just thought it would be appropriate to list it with the other new language features.

 

For more information see MSDN C# Programming Guide

Delegates C Sharp – The Complete Tutorial

Introduction

        Delegate is like a buzz word in C#.NET programming. In this article, I explain delegates, multicast delegates and their usage with the help of simple C# programs.

What is a Delegate?

        Delegate is a type which holds the method(s) reference in an object. It is also referred to as a type safe function pointer. The below figure illustrates the overview of Delegate.

Delegate is a type which holds the method(s) reference in an object. It is also referred to as a type safe function pointer.

Advantages

  • Encapsulating the method’s call from caller
  • Effective use of delegate improves the performance of application
  • Used to call a method asynchronously

Declaration

public delegate type_of_delegatedelegate_name()

Example:

publicdelegate int mydelegate(int delvar1,int delvar2)

Note

  • You can use delegates without parameters or with parameter list
  • You should follow the same syntax as in the method
    (If you are referring to the method with two int parameters and int return type, the delegate which you are declaring should be in the same format. This is why it is referred to as type safe function pointer.)

Sample Program using Delegate

public delegate double Delegate_Prod(int a,int b);
class Class1
{    
  static double fn_Prodvalues(int val1,int val2)    
  {        
    return val1*val2;    
  }    
  static void Main(string[] args)    
  {        //Creating the Delegate Instance        
    Delegate_Prod delObj = new Delegate_Prod(fn_Prodvalues);        
    Console.Write("Please Enter Values");        
    int v1 = Int32.Parse(Console.ReadLine());        
    int v2 = Int32.Parse(Console.ReadLine());        //use a delegate for processing        
    double res = delObj(v1,v2);        
    Console.WriteLine ("Result :"+res);        
    Console.ReadLine();    
  }
}

Explanation

Here I have used a small program which demonstrates the use of delegate.

The delegate “Delegate_Prod” is declared with double return type and accepts only two integer parameters.

Inside the class, the method named fn_Prodvalues is defined with double return type and two integer parameters. (The delegate and method have the same signature and parameter type.)

Inside the Main method, the delegate instance is created and the function name is passed to the delegate instance as follows:

Delegate_Prod delObj = new Delegate_Prod(fn_Prodvalues);

After this, we are accepting the two values from the user and passing those values to the delegate as we do using method:

delObj(v1,v2);

Here delegate object encapsulates the method functionalities and returns the result as we specified in the method.

Multicast Delegate

What is Multicast Delegate?

 

It is a delegate which holds the reference of more than one method.

Multicast delegates must contain only methods that return void, else there is a run-time exception.

Simple Program using Multicast Delegate

delegate void Delegate_Multicast(int x, int y);
Class Class2
{    
 static void Method1(int x, int y)    
 {        
   Console.WriteLine("You r in Method 1");    
 }     
 static void Method2(int x, int y)    
 {        
   Console.WriteLine("You r in Method 2");    
 }    
 public static void Main()  
 {      
   Delegate_Multicast func = new Delegate_Multicast(Method1);     
   func += new Delegate_Multicast(Method2);   
   func(1,2);             // Method1 and Method2 are called     
   func -= new Delegate_Multicast(Method1);     
   func(2,3);             // Only Method2 is called    
 }
}

Explanation

In the above example, you can see that two methods are defined named method1 and method2 which take two integer parameters and return type as void.

In the main method, the Delegate object is created using the following statement:

Delegate_Multicast func = new Delegate_Multicast(Method1);

Then the Delegate is added using the += operator and removed using the -= operator.

For more information see this MSDN C# Programming Guide.

Method Overriding in C#

Method overriding in C# is a feature like the virtual function in C++. Method overriding is a feature that allows you to invoke functions (that have the same signatures) that belong to different classes in the same hierarchy of inheritance using the base class reference. C# makes use of two keywords: virtual and overrides to accomplish Method overriding.

The figure below illustrates the overview of method overriding

 

Method Overriding of Shape ( Circle, Square and Triangle are basically Shapes but having different method to draw each shape)

The concept of method overriding is simple; Circle, Square and Triangle are basic shapes, But the method to draw each of them is different. So circle is a shape but we have set of rules to draw a circle, so we are creating unique method for drawing circle.

Method Overriding in C# – Examples

Let’s understand this through small examples.

P1.cs
class BC
{
  public void Display()
  {
     System.Console.WriteLine("BC::Display");
  }
} 
class DC : BC
{
  new public void Display()
  {
     System.Console.WriteLine("DC::Display");
  }
} 
class Demo
{
  public static void Main()
  {
     BC b;
     b = new BC();
     b.Display();
   }
}
Output
BC::Display

The above program compiles and runs successfully to give the desired output. It consists of a base class BC and a derived class DC. Class BC consists of function Display(). Class DC hides the function Display() it inherited from the base class BC by providing its on implementation of Display(). Class Demo consists of entry-point function Main(). Inside Main() we first create a reference b of type BC. Then we create an object of type BC and assign its reference to reference variable b. Using the reference variable b we invoke the function Display(). As expected, Display() of class BC is executed because the reference variable b refers to the object of class BC.

Now we add a twist of lime to the above program.

P2.cs
class BC
{
  public void Display()
  {
     System.Console.WriteLine("BC::Display");
  }
} 
class DC : BC
{
  new public void Display()
  {
     System.Console.WriteLine("DC::Display");
  }
} 
class Demo
{
  public static void Main()
  {
     BC b;
     b = new BC();
     b.Display();
     b = new DC();
     b.Display();   
   }
}
Output
BC::DisplayBC::Display

Here we are creating an object of Derived class DC and storing its reference in the reference variable b of type BC. This is valid in C#. Next, using the reference variable b we invoke the function Display(). Since b contains a reference to object of type DC one would expect the function Display() of class DC to get executed. But that does not happen. Instead what is executed is the Display() of BC class. That’s because the function is invoked based on type of the reference and not to what the reference variable b refers to. Since b is a reference of type BC, the function Display()of class BC will be invoked, no matter whom b refers to. Take one more example.

P3.cs
class BC
{
  public void Display()
  {
     System.Console.WriteLine("BC::Display");
  }
} 
class DC : BC
{
  new public void Display()
  {
     System.Console.WriteLine("DC::Display");
  }
} 
class TC : BC
{
  new public void Display()
  {
     System.Console.WriteLine("DC::Display");
  }
} 
class Demo
{
  public static void Main()
  {
     BC b;
     b = new BC();
     b.Display();
     b = new DC();
     b.Display();    
     b = new TC();
     b.Display();
   }
}
Output
BC::DisplayBC::DisplayBC::Display

The output of the above program is a receipt of the fact that no matter to whom base class reference b refers, it invokes the functions of the class that matches its type. But doesn’t this sound absurd? If b contains the reference to a particular derived class object, then its supposed to invoke the function of that class. Well, C# helps us do this by the usage of keywords virtual and override as shown in the following program.

P4.cs
class BC
{
  public virtual void Display()
  {
     System.Console.WriteLine("BC::Display");
  }
} 
class DC : BC
{
  public override void Display()
  {
     System.Console.WriteLine("DC::Display");
  }
} 
class Demo
{
  public static void Main()
  {
     BC b;
     b = new BC();
     b.Display();     
     b = new DC();
     b.Display();    
  }
}
Output
BC::DisplayDC::Display

The above program compiles and runs successfully to give the expected desired output. The function Display() of Base class BC is declared as virtual, while the Derived class’s implementation of Display() is decorated with the modifier override. Doing so enables C# to invoke functions like Display() based on objects the reference variable refers to and not the type of reference that is invoking the function. Hence in the above program when b refers to the object of class BC it invokes Display() of BC and then when b refers to the object of class DC it invokes Display() of class DC. Let’s see if this holds true for the third generation of derived classes. Take the following program.

P4.cs
class BC
{
  public virtual void Display()
  {
     System.Console.WriteLine("BC::Display");
  }
} 
class DC : BC
{
  public override void Display()
  {
     System.Console.WriteLine("DC::Display");
  }
} 
class TC : DC
{
  public override void Display()
  {
     System.Console.WriteLine("TC::Display");
  }
} 
class Demo
{
  public static void Main()
  {
     BC b;
     b = new BC();
     b.Display();     
     b = new DC();
     b.Display();     
     b = new TC();
     b.Display();   
  }
}
Output
BC::DisplayDC::DisplayTC::Display

The above program compiles and runs successfully to give the expected desired output. The function Display() of Base class BC is declared as virtual, while the implementation of Display() in successive Derived classes is decorated with the modifier override. Next, we successively create objects of each class and store their reference in base class reference variable b and invoke Display(). The rite versions of Display get invoked based on the object the reference variable refers to. Time for a tiny teaser! Guess what the output would be in the following program?

P5.cs
class BC
{
  public virtual void Display()
  {
     System.Console.WriteLine("BC::Display");
  }
} 
class DC : BC
{
  public override void Display()
  {
     System.Console.WriteLine("DC::Display");
  }
} 
class TC : DC
{ 

} 
class Demo
{
  public static void Main()
  {
     BC b;
     b = new TC();
     b.Display();   
  }
}
Output
DC::Display

Since TC has no implementation of Display(), it inherits Display() from DC as TC is derived from DC. Hence Display() from Derived class DC gets executed. It’s as if the derived class TC looked like this:

class TC 
{
  public override void Display()
  {
     System.Console.WriteLine("DC::Display");
  }
}

to the compiler. Take one more example. Guess what its output will be.

P6.cs
class BC
{
  public virtual void Display()
  {
     System.Console.WriteLine("BC::Display");
  }
} 
class DC : BC
{
  public override void Display()
  {
     System.Console.WriteLine("DC::Display");
  }
} 
class TC : DC
{
  public new void Display()
  {
     System.Console.WriteLine("TC::Display");
  }
} 
class Demo
{
  public static void Main()
  {
     BC b;
     b = new TC();
     b.Display();
  }
}
Output
DC::Display

Agreed that TC defines its own new version of Display(). But its version of display is not invoked as Display() of TC does not override the Display() of the base class. With this understood we are done with Method overriding in C#.

For more information see MSDN Reference Document Method Overriding in C#