Initialize Func <T1, T2> as an extension method
Is it possible to make a Func delegate an extension method? For example, just as you could create a function
bool isSet(this string x) {return x.Length > 0;}
I would like to write something like
Func<string, bool> isSet = (this x => x.Length > 0);
Of course, the above is not syntactically correct. Is there anything like that? If not, is this a limitation in syntax or compilation?
Is it possible to make a Func delegate an extension method?
Not. Extension methods should be declared as regular static methods in high (non-nested) non-general static classes.
It looks like you are trying to create an extension method only for the scope of the method - in C # there is no such concept.
To answer the question in the comments about why this is required, you usually define the isSet function and usually use it as a method call that will have the same effect as your extension method, but with a different syntax.
The difference in syntax in use is only in the fact that you pass the string as a parameter, and do not name it as a method in this string.
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 above (but without this syntax). Then it defines a list of test values ββand iterates over them, generating some output, part of which simply calls isSet(val)
. Func
can be used like this quite happily and should do what you want, I think.