A question on delegates and method parameters

Posted by Srinivas Reddy Thatiparthy on Stack Overflow See other posts from Stack Overflow or by Srinivas Reddy Thatiparthy
Published on 2010-05-06T07:08:29Z Indexed on 2010/05/06 7:18 UTC
Read the original article Hit count: 326

Filed under:
|
|
|
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?

© Stack Overflow or respective owner

Related posts about delegates

Related posts about c#