C# Delegate under the hood question.

Posted by Ted on Stack Overflow See other posts from Stack Overflow or by Ted
Published on 2010-05-05T16:39:31Z Indexed on 2010/05/05 16:48 UTC
Read the original article Hit count: 348

Filed under:
|
|

Hi Guys

I was doing some digging around into delegate variance after reading the following tquestion in SO.

"delegate-createdelegate-and-generics-error-binding-to-target-method" (sorry not allowed to post more than one hyperlink as a newbie here!)

I found a very nice bit of code from Barry kelly at https://www.blogger.com/comment.g?blogID=8184237816669520763&postID=2109708553230166434

Here it is (in a sugared-up form :-)

using System;

namespace ConsoleApplication4
{
    internal class Base
    {
    }

    internal class Derived : Base
    {
    }

    internal delegate void baseClassDelegate(Base b);

    internal delegate void derivedClassDelegate(Derived d);


    internal class App
    {
        private static void Foo1(Base b)
        {
            Console.WriteLine("Foo 1");
        }

        private static void Foo2(Derived b)
        {
            Console.WriteLine("Foo 2");
        }

        private static T CastDelegate<T>(Delegate src)
            where T : class
        {
            return (T) (object) Delegate.CreateDelegate(
                                    typeof (T),
                                    src.Target,
                                    src.Method,
                                    true); // throw on fail
        }

        private static void Main()
        {
            baseClassDelegate a = Foo1; // works fine

            derivedClassDelegate b = Foo2; // works fine

            b = a.Invoke; // the easy way to assign delegate using variance, adds layer of indirection though

            b(new Derived());

            b = CastDelegate<derivedClassDelegate>(a); // the hard way, avoids indirection

            b(new Derived());
        }
    }
}

I understand all of it except this one (what looks very simple) line.

b = a.Invoke; // the easy way to assign delegate using variance, adds layer of indirection though

Can anyone tell me:

  1. how it is possible to call invoke without passing the param required by the static function.
  2. When is going on under the hood when you assign the return value from calling invoke
  3. What does Barry mean by extra indirection (in his comment)

© Stack Overflow or respective owner

Related posts about c#

Related posts about delegates