Tuesday, January 22, 2013

Delegates


Delegates

This part of the C# tutorial is dedicated to delegates.
Delegate A delegate is a form of type-safe function pointer used by the .NET Framework. Delegates are often used to implement callbacks and event listeners. A delegate does not need to know anything about classes of methods it works with.
A delegate is a reference type. But instead of referring to an object, a delegate refers to a method.
Delegates are used in the following cases:
  • Event handlers
  • Callbacks
  • LINQ
  • Implementation of design patterns
There is nothing that is done with delegates that cannot be done with regular methods. Delegates are used, because they bring several advantages. They foster flexibility of the application and code reuse. Like interfaces, delegates let us decouple and generalize our code. Delegates also allow methods to be passed as parameters. When we need to decide which method to call at runtime, we use a delegate. Finally, delegates provide a way of specializing behavior of a class without subclassing it. Classes may have complex generic behavior, but are still meant to be specialized. Classes are specialized either through inheritance or via delegates.

Using delegates

Simple delegates We will have some simple examples showing, how to use delegates.
using System;   


delegate void Mdelegate();

public class CSharpApp
{
    static void Main()
    {
        Mdelegate del = new Mdelegate(Callback);
        del();
    }

    static void Callback()
    {
        Console.WriteLine("Calling callback");
    }
}
We declare a delegate, create an instance of the delegate and invoke it.
delegate void Mdelegate();
This is our delegate declaration. It returns no value and takes no parameters.
Mdelegate del = new Mdelegate(Callback);
We create an instance of the delegate. When called, the delegate will invoke the static Callback() method.
del();
We call the delegate.
$ ./simple.exe 
Calling callback
Output.

Simplified syntax We can use a different syntax for creating and using a delegate.
using System;   


delegate void Mdelegate();

public class CSharpApp
{
    static void Main()
    {
        Mdelegate del = Callback;
        del();
    }

    static void Callback()
    {
        Console.WriteLine("Calling callback");
    }
} 
We can save some typing when creating an instance of a delegate. It was introduces in C# 2.0.
Mdelegate del = Callback;
This is another way of creating a delegate. We save some typing.

Anonymous methods It is possible to use anonymous methods with delegates.
using System;   


delegate void Mdelegate();

public class CSharpApp
{
    static void Main()
    {
        Mdelegate del = delegate { 
            Console.WriteLine("Anonymous method"); 
        };

        del();
    }
} 
We can omit a method declaration when using an anonymous method with a delegate. The method has no name and can be invoked only via the delegate.
Mdelegate del = delegate { 
    Console.WriteLine("Anonymous method"); 
};
Here we create a delegate, that points to an anonymous method. The anonymous method has a body enclosed by { } characters, but it has no name.

A delegate can point to different methods over time.
using System;


public delegate void NameDelegate(string msg);

public class Person 
{
    public string firstName;
    public string secondName;

    public Person(string firstName, string secondName)
    { 
        this.firstName = firstName;
        this.secondName = secondName;
    }

    public void ShowFirstName(string msg)
    {
        Console.WriteLine(msg + this.firstName);
    }

    public void ShowSecondName(string msg)
    {
        Console.WriteLine(msg + this.secondName);
    }
}

public class CSharpApp
{
    public static void Main()
    {
        Person per = new Person("Fabius", "Maximus");       

        NameDelegate nDelegate = new NameDelegate(per.ShowFirstName);
        nDelegate("Call 1: ");

        nDelegate = new NameDelegate(per.ShowSecondName);
        nDelegate("Call 2: ");     
    }
}
In the example we have one delegate. This delegate is used to point to two methods of the Person class. The methods are called with the delegate.
public delegate void NameDelegate(string msg);
The delegate is created with a delegate keyword. The delegate signature must match the signature of the method being called with the delegate.
NameDelegate nDelegate = new NameDelegate(per.ShowFirstName);
nDelegate("Call 1: ");
We create an instance of a new delegate, that points to the ShowFirstName() method. Later we call the method via the delegate.
$ ./simpledelegate.exe 
Call 1: Fabius
Call 2: Maximus
Both names are printed via the delegate.

Multicast delegate Multicast delegate is a delegate which holds a reference to more than one method. Multicast delegates must contain only methods that return void, else there is a run-time exception.
using System;   


delegate void Mdelegate(int x, int y);

public class Oper
{
    public static void Add(int x, int y)
    {
        Console.WriteLine("{0} + {1} = {2}", x, y, x + y);
    }

    public static void Sub(int x, int y)
    {
        Console.WriteLine("{0} - {1} = {2}", x, y, x - y);
    }
}

public class CSharpApp
{
    static void Main()
    {
        Mdelegate del = new Mdelegate(Oper.Add);

        del += new Mdelegate(Oper.Sub);
        del(6, 4);            
        del -= new Mdelegate(Oper.Sub);
        del(2, 8);            
    }
}
This is an example of a multicast delegate.
delegate void Mdelegate(int x, int y);
Our delegate will take two parameters. We have an Oper class, which has two static methods. One adds two values the other one subtracts two values.
Mdelegate del = new Mdelegate(Oper.Add);
We create an instance of our delegate. The delegate points to the static Add() method of the Oper class.
del += new Mdelegate(Oper.Sub);
del(6, 4);  
We plug another method to the existing delegate instance. The first call of the delegate invokes two methods.
del -= new Mdelegate(Oper.Sub);
del(2, 8);    
We remove one method from the delegate. The second call of the delegate invokes only one method.
$ ./multicast.exe 
6 + 4 = 10
6 - 4 = 2
2 + 8 = 10
Output.

Delegates as method parameters

Delegates can be used as method parameters.
using System;   


delegate int Arithm(int x, int y);

public class CSharpApp
{
    static void Main()
    {
        DoOperation(10, 2, Multiply);
        DoOperation(10, 2, Divide);
    }

    static void DoOperation(int x, int y, Arithm del)
    {
        int z = del(x, y);
        Console.WriteLine(z);
    }

    static int Multiply(int x, int y)
    {
        return x * y;
    }

    static int Divide(int x, int y)
    {
        return x / y;
    }
} 
We have a DoOperation() method, which takes a delegate as a parameter.
delegate int Arithm(int x, int y);
This is a delegate declaration.
static void DoOperation(int x, int y, Arithm del)
{
    int z = del(x, y);
    Console.WriteLine(z);
}
This is DoOperation() method implementation. The third parameter is a delegate. The DoOperation() method calls a method, which is passed to it as a third parameter.
DoOperation(10, 2, Multiply);
DoOperation(10, 2, Divide);
We call the DoOperation() method. We pass two values and a method to it. What we do with the two values, depends on the method that we pass. This is the flexibility that come with using delegates.

Events

Events are messages triggered by some action. Click on the button or tick of a clock are such actions. The object that triggers an event is called a sender and the object that receives the event is called a receiver.
By convention, event delegates in the .NET Framework have two parameters, the source that raised the event and the data for the event.
using System;   


public delegate void OnFiveHandler(object sender, EventArgs e);

class FEvent { 
    public event OnFiveHandler FiveEvent;
 
    public void OnFiveEvent() 
    { 
        if(FiveEvent != null) 
            FiveEvent(this, EventArgs.Empty); 
    } 
} 

public class CSharpApp
{
    static void Main()
    {
        FEvent fe = new FEvent();
        fe.FiveEvent += new OnFiveHandler(Callback);

        Random random = new Random();

        for (int i = 0; i<10 5="" callback="" console.writeline="" e="" event="" eventargs="" fe.onfiveevent="" i="" if="" int="" ive="" object="" occured="" pre="" public="" rn="=" sender="" static="" void="">
We have a simple example in which we create and launch an event. An random number is generated. If the number equals to 5 a FiveEvent event is generated.
public event OnFiveHandler FiveEvent;
An event is declared with a event keyword.
fe.FiveEvent += new OnFiveHandler(Callback);
Here we plug the event called FiveEvent to the Callback method. In other words, if the ValueFive event is triggered, the Callback() method is executed.
public void OnFiveEvent() 
{ 
    if(FiveEvent != null) 
        FiveEvent(this, EventArgs.Empty); 
} 
When the random number equals to 5, we invoke the OnFiveEvent() method. In this method, we raise the FiveEvent event. This event carries no arguments.
$ ./simpleevent.exe 
3
0
5
Five Event occured
0
5
Five Event occured
2
3
4
4
0
Outcome of the program might look like this.

Complex event example Next we have a more complex example. This time we will send some data with the generated event.
using System;   


public delegate void OnFiveHandler(object sender, FiveEventArgs e);

public class FiveEventArgs : EventArgs
{
    public int count;
    public DateTime time;

    public FiveEventArgs(int count, DateTime time)
    {
        this.count = count;
        this.time = time;
    }
}

public class FEvent 
{ 
    public event OnFiveHandler FiveEvent;

    public void OnFiveEvent(FiveEventArgs e) 
    { 
        FiveEvent(this, e); 
    } 
} 

public class RandomEventGenerator
{
    public void Generate()
    {
        int count = 0;
        FiveEventArgs args;

        FEvent fe = new FEvent();
        fe.FiveEvent += new OnFiveHandler(Callback);

        Random random = new Random();

        for (int i = 0; i<10 5="" args="" at="" callback="" class="" console.writeline="" count="" csharpapp="" datetime.now="" e.count="" e.time="" e="" event="" fe.onfiveevent="" fiveeventargs="" i="" if="" int="" ive="" main="" object="" occured="" pre="" public="" randomeventgenerator="" reg.generate="" reg="new" rn="=" sender="" static="" void="">
We have four classes. FiveEventArgs carries some data with the event object. The FEvent class encapsulates the event object. RandomEventGenerator class is responsible for random number generation. It is the event sender. Finally the CSharpApp class, which is the main application object and has the Main() method.
public class FiveEventArgs : EventArgs
{
    public int count;
    public DateTime time;
...
The FiveEventArgs carries data inside the event object. It inherits from the EventArgs base class. The count and time members are data that will be initialized and carried with the event.
if (rn == 5)
{    
    count++;
    args = new FiveEventArgs(count, DateTime.Now);
    fe.OnFiveEvent(args);
}
If the generated random number equals to 5, we instantiate the FiveEventArgs class with the current count and DateTime values. The count variable counts the number of times this event was generated. The DateTime value holds the time, when the event was generated.
$ ./complexevent.exe 
2
2
3
5
Five event 1 occured at 11/7/2010 12:13:59 AM
5
Five event 2 occured at 11/7/2010 12:13:59 AM
1
1
0
5
Five event 3 occured at 11/7/2010 12:13:59 AM
5
Five event 4 occured at 11/7/2010 12:13:59 AM
This is the ouput I got on my computer.

Predefined delegates

The .NET framework has several built-in delegates that a reduce the typing needed and make the programming easier for developers.
Action delegate An action delegate encapsulates a method that has no parameters and does not return a value.
using System;   

public class CSharpApp
{
    static void Main()
    {
        Action act = ShowMessage;
        act();
    }

    static void ShowMessage()
    {
        Console.WriteLine("C# language");
    }
} 
Using predefined delegates further simplifies programming. We do not need to declare a delegate type.
Action act = ShowMessage;
act();
We instantiate an action delegate. The delegate points to the ShowMessage() method. When the delegate is invoked, the ShowMessage() method is executed.

Action delegate There are multiple types of action delegates. For example, the Action delegate encapsulates a method that takes a single parameter and does not return a value.
using System;   

public class CSharpApp
{
    static void Main()
    {
        Action act = ShowMessage;
        act("C# language");
    }

    static void ShowMessage(string message)
    {
        Console.WriteLine(message);
    }
} 
We modify the previous example to use the action delegate, that takes one parameter.
Action act = ShowMessage;
act("C# language");
We create an instance of the Action delegate and call it with one parameter.

Predicate delegate A predicate is a method that returns true or false. A predicate delegate is a reference to a predicate. Predicates are very useful for filtering a list of values.
using System;
using System.Collections.Generic;

public class CSharpApp
{
    static void Main()
    {
        List list = new List { 4, 2, 3, 0, 6, 7, 1, 9 };

        Predicate predicate = greaterThanThree;

        List list2 = list.FindAll(predicate);

        foreach ( int i in list2)
        {
            Console.WriteLine(i);
        }
    }

    static bool greaterThanThree(int x)
    {
        return x > 3;
    }
}
We have a list of integer values. We want to filter all numbers, that are bigger than three. For this, we use the predicate delegate.
List list = new List { 4, 2, 3, 0, 6, 7, 1, 9 };
This is a generic list of integer values.
Predicate predicate = greaterThanThree;
We create an instance of a predicate delegate. The delegate points to a predicate, a special method that returns true or false.
List list2 = list.FindAll(predicate);
The FindAll() method retrieves all the elements that match the conditions defined by the specified predicate.
static bool greaterThanThree(int x)
{
    return x > 3;
}
The predicate returns true for all values, that are greater than three.
This part of the C# tutorial was dedicated to the delegates.

Garbage Collection in .Net framework


Introduction:
The Garbage collection is very important technique in the .Net framework to free the unused managed code objects in the memory and free the space to the process. I will explain about the basics of the Garbage collection in this article.

Garbage Collection in .Net framework

The garbage collection (GC) is new feature in Microsoft .net framework. When we have a class that represents an object in the runtime that allocates a memory space in the heap memory. All the behavior of that objects can be done in the allotted memory in the heap. Once the activities related to that object is get finished then it will be there as unused space in the memory.

The earlier releases of Microsoft products have used a method like once the process of that object get finished then it will be cleared from the memory. For instance Visual Basic, An object get finishes that work then there we have to define a "nothing" to that object. So, it clears the memory space to the processors.

Microsoft was planning to introduce a method that should automate the cleaning of unused memory space in the heap after the life time of that object. Eventually they have introduced a new technique "Garbage collection". It is very important part in the .Net framework. Now it handles this object clear in the memory implicitly. It overcomes the existing explicit unused memory space clearance.

Garbage Collection

The heap memory is divided into number of generations. Normally it is three generations. The Generation 0 is for short live objects, Generation 1 is for medium live objects which are moved from Generation 0. Generation 3 is mostly stable objects. 

When an object is created then it will allocate the memory space which will be higher. It will be in the Generation 0 and the memory allocation will be continuous without any space between the generations of garbage collectors.

How it works

Implicit Garbage Collection should be handled by the .Net framework. When object is created then it will be placed in the Generation 0. The garbage collection uses an algorithm which checks the objects in the generation, the objects life time get over then it will be removed from the memory. The two kinds of objects. One is Live Objects and Dead Objects. The Garbage collection algorithm collects all unused objects that are dead objects in the generation. If the live objects running for long time then based on that life time it will be moved to next generation.

The object cleaning in the generation will not take place exactly after the life time over of the particular objects. It takes own time to implement the sweeping algorithm to free the spaces to the process.

Exception Handling

The Garbage collection has designed such a way that it can be implicitly handling to collect the free spaces in memory. But as I said it takes own time to uses the algorithm to collect unused objects in the memory.

If we want to forces to collect unused objects or explicitly release particular object from the momory.The code allows us to clear the object from the heap immediately.

When it happens

The garbage collector periodically checks the heap memory to reclaim the objects when the object has no valid references in the memory.

When an object is created then it will allocate the memory in the heap then it checks the available space for the newly created objects, if the available space is not adequate to allot the space then it automatically garbage collect the unused objects. If all are valid referenced objects then it gets additional space from the processor.
 

If the object has reference with managed code objects then it will not free the memory space. However it cannot control the reference with unmanaged code objects, when application forces to collect the unused objects. But it can be achieved to write the explicit coding to avoid managed objects reference with unmanaged objects. 

Example code to know more about Garbage Collection

The Microsoft framework System namespace have the GC class, which exposes more method and property about garbage collection.

MaxGeneration

This property in the GC class returns the total number of generations.
 
 
using System;
class GCExample1
{
    public static void Main(string[] args)
    {
        try
        {
            Console.WriteLine("GC Maximum Generations:" + GC.MaxGeneration);
        }
        catch (Exception oEx)
        {
            Console.WriteLine("Error:" + oEx.Message);
        }
    }
}
MaxGeneration property will return the highest generation in the garbage collection. It will be counted as total number of generations in the GC class which starts from 0.Here it has returned 2 as maxGeneration. That means totally three generations in the Garbage Collection. They are Generation 0, Generation 1 and Generation 2.  
GCExample1.JPG

GetTotalMemory and GetGeneration

using System;
class BaseGC
{
    public void Display()
    {
        Console.WriteLine("Example Method");
    }
}

class GCExample2
{
    public static void Main(string[] args)
    {
        try
        {
            Console.WriteLine("Total Memory:" + GC.GetTotalMemory(false));
            BaseGC oBaseGC = new BaseGC();
            Console.WriteLine("BaseGC Generation is :" + GC.GetGeneration(oBaseGC));
            Console.WriteLine("Total Memory:" + GC.GetTotalMemory(false));
        }
        catch (Exception oEx)
        {
            Console.WriteLine("Error:" + oEx.Message);
        }
    }} 
Here GetTotalMemory shows the total number of memory occupied by the various resources. Here I have added one more managed code objects in the heap memory. After adding, the size of the memory has increased. 
The GetGeneration method will find out the particular managed object in the which generation. Here it shows the Object oBaseGC in the 0th generation.
 
GCExample2.JPG
CollectionCount and Collect 
using System;
class Calci
{
    public int Add(int a, int b)
    {
        return (a + b);
    }
    public int Sub(int a, int b)
    {
        return (a - b);
    }
    public int Multi(int a, int b)
    {
        return (a * b);
    }
    public int Divide(int a, int b)
    {
        return (a / b);
    }
}

class GCExample3
{
    public static void Main(string[] args)
    {
        Calci oCalci = new Calci();
        Console.WriteLine("Calci object is now on " + GC.GetGeneration(oCalci) + " Generation");
        Console.WriteLine("Garbage Collection Occured in 0th Generation:" +GC.CollectionCount(0));
        Console.WriteLine("Garbage Collection Occured in 1th Generation:" +GC.CollectionCount(1));
        Console.WriteLine("Garbage Collection Occured in 2th Generation:" +GC.CollectionCount(2));
        GC.Collect(0);
        Console.WriteLine("Garbage Collection Occured in 0th Generation:" +GC.CollectionCount(0));
    }
} 
GCExample33.JPG
The CollectionCount helps us to find out the generation wise garbage collection occurred. As we know there are totally three generations in the garbage collector. Here I have passed argument as one for know the first generation. Initially it was 0. Then through the code I have collected the unused objects in the 0th generation. Again I have checked the CollectionCount in the 0thgeneration. Now it says 1.

The Collect method used to collect the unreferenced objects in the heap memory. It will clear the object and reclaim the memory space.

Conclusion:

So far I explained about the basics of the garbage collection. I have not explained about the explicit handling of the garbage collection ways and some of the methods in the GC class. I will be explaining the part 2 of this article soon. If you found any mistakes or wrong explanations then please indicate me. So that I can update this article.

Sunday, January 20, 2013

Csharp / C# Multicast Delegate example


using System;
 
//observation: A delegate which takes two paramter of integer type.
public delegate void fnTwoInteger(int x,int y);
 
public class DelegateExample
{
    public static void Main()
    {
        ExmapleClass obj = new ExmapleClass();
 
        fnTwoInteger pointer=null;
 
        //observation: adding more than one function called multicast delegate.
        pointer += new fnTwoInteger(obj.Add);
 
        pointer += new fnTwoInteger(obj.Multiply);
 
        pointer(52, 72);
 
        Console.ReadLine();
    }
}
 
public class ExmapleClass
{
    public void Add(int x, int y)
    {
        Console.WriteLine("The sum is: " + (x + y));
    }
 
    public void Multiply(int x, int y)
    {
        Console.WriteLine("The product is: " + (x * y));
    }
}
Output:
The sum is: 124
The product is: 3744