Is it possible to declare generic delegate with no parameters?
Asked Answered
A

5

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?

Aedile answered 7/12, 2011 at 11:57 Comment(0)
N
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;
Nourishment answered 7/12, 2011 at 12:3 Comment(0)
B
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

Budge answered 7/12, 2011 at 11:59 Comment(1)
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?Nourishment
S
3

Use Action delegate type.

Sorensen answered 7/12, 2011 at 11:58 Comment(0)
E
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; });.

Everything answered 7/12, 2011 at 12:3 Comment(0)
W
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();
}
Whistle answered 2/7, 2018 at 14:10 Comment(2)
Do mention how your code is different from other answers (this one using Lambda instead of Action/Func delegates)Lithograph
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:Whistle

© 2022 - 2024 — McMap. All rights reserved.