Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 801
Exitos Avatar asked Dec 07 '11 11:12

Exitos


People also ask

Can delegates also be made generic?

Delegates defined within a generic class can use the generic class type parameters in the same way that class methods do. Generic delegates are especially useful in defining events based on the typical design pattern because the sender argument can be strongly typed and no longer has to be cast to and from Object.

Can we pass delegate as parameter?

You can pass methods as parameters to a delegate to allow the delegate to point to the method. Delegates are used to define callback methods and implement event handling, and they are declared using the “delegate” keyword. You can declare a delegate that can appear on its own or even nested inside a class.

What are the three types of generic delegates in C#?

Func, Action and Predicate are generic inbuilt delegates present in System namespace. All three can be used with method, anonymous method and lambda expression.


4 Answers

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;
like image 118
svick Avatar answered Oct 20 '22 18:10

svick


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

like image 20
dknaack Avatar answered Oct 20 '22 17:10

dknaack


Use Action delegate type.

like image 36
Novakov Avatar answered Oct 20 '22 19:10

Novakov


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

like image 31
lbergnehr Avatar answered Oct 20 '22 17:10

lbergnehr