Exitos
Exitos

Reputation: 29720

Is it possible to declare generic delegate with no parameters?

I have...

Func<string> del2 = new Func<string>(MyMethod);

and I really want to do..

Func<> del2 = new Func<>(MyMethod);

so the return type of the callback method is void. Is this possible using the generic type func?

Upvotes: 7

Views: 18048

Answers (5)

TheSlazzer
TheSlazzer

Reputation: 31

Here is a code example using Lambda expressions instead of Action/Func delegates.

delegate void TestDelegate();

static void Main(string[] args)
{
  TestDelegate testDelegate = () => { /*your code*/; };

  testDelegate();
}

Upvotes: 3

dknaack
dknaack

Reputation: 60468

Yes a function returning void (no value) is a Action

public Test()
{
    // first approach
    Action firstApproach = delegate
    {
        // do your stuff
    };
    firstApproach();

    //second approach 
    Action secondApproach = MyMethod;
    secondApproach();
}

void MyMethod()
{
    // do your stuff
}

hope this helps

Upvotes: 8

svick
svick

Reputation: 244767

The Func family of delegates is for methods that take zero or more parameters and return a value. For methods that take zero or more parameters an don't return a value use one of the Action delegates. If the method has no parameters, use the non-generic version of Action:

Action del = MyMethod;

Upvotes: 20

lbergnehr
lbergnehr

Reputation: 1598

In cases where you're 'forced' to use Func<T>, e.g. in an internal generic API which you want to reuse, you can just define it as new Func<object>(() => { SomeStuff(); return null; });.

Upvotes: 3

Novakov
Novakov

Reputation: 3095

Use Action delegate type.

Upvotes: 3

Related Questions