A question on delegates and method parameters
- by Srinivas Reddy Thatiparthy
public class Program
{
delegate void Srini(string param);
static void Main(string[] args)
{
Srini sr = new Srini(PrintHello1);
sr += new Srini(PrintHello2); //case 2:
sr += new Srini(delegate(string o) { Console.WriteLine(o); });
sr += new Srini(delegate(object o) { Console.WriteLine(o.ToString()); }); //case 4:
sr += new Srini(delegate { Console.WriteLine(“This line is accepted,though the method signature is not Comp”); });//case 5
sr("Hello World");
Console.Read();
}
static void PrintHello1(string param)
{
Console.WriteLine(param);
}
static void PrintHello2(object param)
{
Console.WriteLine(param);
}
}
Compiler doesn't complain about the case 2(see the comment),well,the reason is straight forward since string inherits from object. ,along the same lines ,Why is it complaining for anonymous method types(see the comment //case 4:) that “Cannot convert anonymous method to delegate type 'DelegateTest.Program.Srini' because the parameter types do not match the delegate parameter types” where as in case of normal method it doesn't ?or am i comparing apples with oranges?
Another case is why is it accepting anonymous method without parameters?