7

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?

svick
  • 236,525
  • 50
  • 385
  • 514
Exitos
  • 29,230
  • 38
  • 123
  • 178

5 Answers5

20

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;
svick
  • 236,525
  • 50
  • 385
  • 514
8

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

dknaack
  • 60,192
  • 27
  • 155
  • 202
  • 2
    Your code wouldn't compile. You can't just leave the type parameters like that. And why do you have both `Action` and `Func` in your code? – svick Dec 07 '11 at 12:00
3

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();
}
TheSlazzer
  • 31
  • 3
  • 1
    Do mention how your code is different from other answers (this one using Lambda instead of Action/Func delegates) – NitinSingh Jul 02 '18 at 14:24
  • Do you mean editing my proposed answer by adding "here is a code example using Lambda expressions instead of Action/Func delegates" or do you want me to justify me posting my answer Feeling it is a duplicate of another answer? Any way thank you for your feedback! - I'm new D: – TheSlazzer Jul 02 '18 at 14:48
3

Use Action delegate type.

svick
  • 236,525
  • 50
  • 385
  • 514
Novakov
  • 3,055
  • 1
  • 16
  • 32
3

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; });.

lbergnehr
  • 1,578
  • 11
  • 15