Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

incompatible anonymous function signature in C#?

Tags:

c#

.net

I want to create an extension method which I can invoke on an object .

The return value will be defined by a function.

Something like this : ( this is just an example )

bool isMature= thePerson.Age.Apply<bool>(d =>   {    if (d >18) return true;
                                                        return false;
                                                 })

and here is the extension method :

  public static Tout Apply<Tout>(this Object obj, Func< Tout> f)  
        {

            return f( );
        }

The error : incompatible anonymous function signature

What am I doing wrong ?

like image 972
Royi Namir Avatar asked Oct 15 '25 16:10

Royi Namir


2 Answers

Your method takes just a Func<Tout> - which is a function taking no parameters, but returning a value.

Your lambda expression has a parameter (d) - and it looks like you're assuming that's an integer. It's not clear what you're trying to do, but if you want to use a parameter in the lambda expression, you're going to have to change the signature from Func<TResult> to Func<TArg, TResult> or something similar - and provide an argument in the invocation.

like image 129
Jon Skeet Avatar answered Oct 17 '25 06:10

Jon Skeet


If looks like you're expecting the input to the delegate instance to be the property value, so you would need to change the definition of the extension method to take this argument:

public static TOut ToFunc<TProperty, TOut>(this TProperty obj, Func<TProperty, TOut> f)  
{
   return f(obj);
}

// Usage
bool isMature = thePerson.Age.ToFunc<int, bool>(d => d > 18);

It seems a strange approach whatever the problem is.

like image 29
devdigital Avatar answered Oct 17 '25 06:10

devdigital