Arithmomaniac
Arithmomaniac

Reputation: 4794

Initialize Func<T1,T2> as an extension method

Is it possible to make a Func delegate an extension method? For example, just like you could create the function

bool isSet(this string x) {return x.Length > 0;}

I'd like to be able to write something like

Func<string, bool> isSet = (this x => x.Length > 0);

Of course, the above is not syntactically correct. Is there anything that is? If not, is that a limitation in syntax or compilation?

Upvotes: 6

Views: 4077

Answers (3)

Chris
Chris

Reputation: 27599

To answer the question in comments on why this is wanted you coudl define the isSet func normally and just use that as a method call which will have the same effect as your extension method but with different syntax.

The syntax difference in use is purely that you'll be passing the string in as a parameter rather than calling it as a method on that string.

A working example:

public void Method()
{
    Func<string, bool> isSet = (x => x.Length > 0);

    List<string> testlist = new List<string>() {"", "fasfas", "","asdalsdkjasdl", "asdasd"};
    foreach (string val in testlist)
    {
        string text = String.Format("Value is {0}, Is Longer than 0 length: {1}", val, isSet(val));
        Console.WriteLine(text);
    }
}

This method defines isSet as you have above (but without the this syntax). It then defines a list of test values and iterates over them generating some output, part of which is just calling isSet(val). Funcs can be used like this quite happily and should do what you want I'd think.

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1500055

Is it possible to make a Func delegate an extension method?

No. Extension methods have to be declared as normal static methods in top-level (non-nested) non-generic static classes.

It looks like you would be trying to create an extension method only for the scope of the method - there's no concept like that in C#.

Upvotes: 7

Philip Daubmeier
Philip Daubmeier

Reputation: 14934

Short answer: no, thats not possible.

Extension methods are syntactic sugar and can only be defined under certain circumstances (static method inside a static class). There is no equivalent of this with lambda functions.

Upvotes: 14

Related Questions