Monday, October 7, 2013

Delegates in C# and the reason for "Type Safe"

Delagates are known as type safe function pointers. Now now dont start to worry about what the hell is "type safe". Observer the following code snippet for a while. You'll realise the familiarity of the code.

What is a delegate?
delegate is a type safe function pointer. Using delegates you can pass methods as parameters. To pass a method as a parameter, to a delegate, the signature of the method must match the signature of the delegate. This is why, delegates are called type safe function pointers.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Deligates
{
    public delegate void DelegateFunction(string temp);
    class Program
    {
        public static void Main(string[] args)
        {
            DelegateFunction del = new DelegateFunction(functionOne);
            del("this is the delegate message");
        }

        public static void functionOne(string msg) 
        {
            Console.WriteLine(msg);
            Console.ReadLine(); // to hold the screen
        }
    }
}


To the costructor of the delegate, you pass the name of the function to, which you want to delegate teh point from.
            DelegateFunction del = new DelegateFunction(functionOne);

What/Why it is called 'type safe'?
The delegate checks for the return type in the function header. not only the parameter type which is passing in.

If the function header is like
            public static string functionOne(string msg) 
instead of
            public static void functionOne(string msg)

when delegate is defined as
            public delegate void DelegateFunction(string temp);
it will the return type of the signature and throws an error because it expects a void (non return). The signature of the delegate should match the signature of the function to which it points. If the signature of the method does not match, the compiler will throw an error. This is why the delegates are called as type safe function pointer, coz it depends on the type to act as a pointer in function.

Delegates gives the exposure of flexibility for the real time projects.


No comments:

Post a Comment