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?

+6
source share
3 answers

Short answer: no, this is not possible.

Extension methods are syntactic sugar and can only be defined under certain circumstances (static method inside a static class). This is not equivalent to lambda functions.

+14
source

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.

+7
source

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.

+3
source

Source: https://habr.com/ru/post/918963/


All Articles