Generic Delagates
No wonder the output would be 300.
Next I am planning to give a brief introduction about general purpose generic delegate in C# 3.0. They are,
Func<>, Action<>, Predicate<>.
But before that I will explain what a generic delegate means. I will begin with an example. Hope readers is aware about the basics of generics.
public delegate TResult MyGenericDelagete<in T1,in T2,out TResult>(T1 arg1,T2 arg2);
Here MyGenericDelagete is a generic delegate which accepts two input parameters and returns something. Input parameters are generic , means it can accept any type but once specified a type then it’s type safe. For example if I create type of this delegate as
MyGenericDelagete<int,int,string> mydel
Now I can point only method which accepts two input parameters of type “int” and return “string”. So the entire code looks like,
public delegate TResult MyGenericDelagete<in T1,in T2,out TResult>(T1 arg1,T2 arg2);
static void Main(string[] args)
{
MyGenericDelagete<int, int, string> mydel = MyMethod;
Console.WriteLine(mydel(100,200));
Console.ReadKey();
}
public static string MyMethod(int a, int b)
{
return Convert.ToString(a + b);
}
I am going to write lambda for the same,
public delegate TResult MyGenericDelagete<in T1,in T2,out TResult>(T1 arg1,T2 arg2);
static void Main(string[] args)
{
MyGenericDelagete<int, int, string> mydel = (a,b)=>Convert.ToString(a+b);
Console.WriteLine(mydel(100,200));
Console.ReadKey();
}
public static string MyMethod(int a, int b)
{
return Convert.ToString(a + b);
}
No comments:
Post a Comment