Tuesday, October 2, 2012

Delegate in c#


Delegate is an object that can refer to a method.

When we are creating delegates, we are creating an object that can hold a reference to a method; it necessarily means that a delegate can invoke the method to which it refers. 

As the delegate refers to a method, the same delegates can be used to call multiple methods just by changing the method name at the run time; provided the method (instance or static) match the signature and return type.

Confused? not a problem, just go through below code snippet of code behind (DelegatesPage.aspx.cs) of my DelegatesPage.aspx page.

public partial class DelegatesPage : System.Web.UI.Page
{
delegate int Add(int x);
protected void Page_Load(object sender, EventArgs e)
{
Add a = Sum;
Response.Write(a(6).ToString());
Response.Write("<br />");
a = Minus;
Response.Write(a(6).ToString());
}

int Sum(int a)
{
return a + a;
}

int Minus(int b)
{
return b - b;
}
}
In the above code snippet, we have declared a delegates named Add that accepts one parameter of integer type. In the Page_Load event, we are assigned Sum method (we will define & implement this method later on) to the delegates object "a". That means that now a can be used to invoke the Sum method. In the very next line, we used "a" that is nothing but the object of delegate Add to call the Sum method. As the Sum method accepts one parameter so we are calling "a" with one parameter "6".

As the Sum method simply add the values are return so calling "a(6)" will return 12.

As I said earlier, the delegate simply refers a method so the same delegate can be used to refer another method and next I have referred Minus method (defined and implemented later on) and again we are calling Minus method just by using the delegate object that gives 0 result.


What is Multicast delegates?

As the name suggest (Multicast), it means multiple so A delegate that refers multiple methods is called Multicast delegates. Calling the object of the delegates automatically call all method referred to this delegate. These methods can be attached and detached using "+=" and "-=" to the instance of the delegate.

In case a delegate returns a value (as in the case of above delegate), the value returned by last method becomes the return value of the entire delegate invocation methods.

public partial class DelegatesPage : System.Web.UI.Page
{
// multi-cast delegates
delegate void Add(int x);
protected void Page_Load(object sender, EventArgs e)
{
Add a = Sum;
a += Minus;
a(6);
}

void Sum(int a)
{
Response.Write(a + a);
Response.Write("<br />");
}

void Minus(int b)
{
Response.Write(b - b);
}
}

In the above code snippet, as you can see that we have a Delegate named "Add" that accepts two parameter but does not return any value as it is void.

In the Page_Load event, we have created the object of the delegate and assigned Sum method; in the very next line we have attached one more method called Minus to the same delegates using "+=" operator.

Now calling the delegates object, simply executes both Sum and Minus method and gives respective results. So we will get 12 and 0 result.  If you have consumed WCF services, you must have come across multicast delegates scenario.


When to use Delegates?

All this looks fine, now the important question is why and when to use delegates? As per MSDN

Use a delegate when:
  • An eventing design pattern is used.
  • It is desirable to encapsulate a static method.
  • The caller has no need access other properties, methods, or interfaces on the object implementing the method.
  • Easy composition is desired.
  • A class may need more than one implementation of the method.
Sounds complicated? In simple term Delegates are basically used in
  1. Abstracting and encapsulating methods
  2. Callback mechanism
  3. Asynchronous programming
  4. Sequential programming etc.

Monday, September 10, 2012

Static in c#

Static in c#
Static Keyword enforce not to create the constructors.Only one copy of static fields and events exists, and static methods and properties can only access static fields and static events.It is not possible to create instances of a static class using the new keyword.Instead, you will access members of the static class by using the class name.

Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.Static class are sealed,which means that they cannot be inherited and cannot inherit from any class other than System.Object and can have only static members,static properties and Static methods.

A static member belongs to the class rather than to the objects of the class.You can't use this keyword with static, as it will not initialize. Static members are shared level and are not initiated.

Important Points on static
1.If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running.
2.Property available to callers at any time, even if no instance of the class exists.
3.Only classes can be declared as static and not structs.
4.You can't use this keyword with static, as it will not initialize. Static members are shared level and are not initiated.
5.Static methods can be public or private.
6.Static modifier cannot used with indexers, destructors, or types.

Example:
public static class Calculation
    {
        public static double ADD(double i, double j)
        {
            return i + j;
        }
    }
class Program
   {
static void Main(string[] args)
        {
            //Error:- Cannot create an instance of the static class'Calculation'
            //Calculation cal = new Calculation();
            double Res= Calculation.ADD(10, 20);
            Console.WriteLine("Add {0}", Res);
 }
   }
Result:
Add 30