asynts
asynts

Reputation: 2423

Can delegates wrap classes in C#?

In C++ we have the std::function type which can be used to wrap lambdas, functions and even custom classes. Here is an example of a custom class wrapped in std::function:

#include <functional>

struct A {
    void operator()() {
    }
};

std::function<void()> a = A();

I though the same was possible with delegates in C# but, I can not get it to work:

class Program
{
    delegate void Foo();

    class Bar
    {
        public void Invoke()
        {

        }
    }

    static void Main()
    {
        new Foo(new Bar()); // CS0149: Method name expected
    }
}

I am convinced that this has to be possible somehow, because the delegate operator internally creates a new class that inherits from System.Delegate which suggests that I can create my own type to do the same somehow.

Upvotes: 0

Views: 35

Answers (1)

Jasper Kent
Jasper Kent

Reputation: 3676

Simple answer is 'no' because C# doesn't have an operator() in the way C++ does.

However, a lambda can be used to store not just a function, but a function on a specific object.

class Program
{
    delegate void Foo();

    class Bar
    {
        public void Invoke()
        {

        }
    }

    static void Main()
    {
        var f = new Foo(new Bar().Invoke); 
    }
}

The difference is simply that in C# you have to specify the method name, rather than there being a default.

Also worth noting that similarly to C++, C# has generics to help this, so we can cut out the Foo declaration altogether:

var f = new Action(new Bar().Invoke);

Upvotes: 1

Related Questions