Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if MethodInfo represents a lambda expression

How does one determine if a MethodInfo represents the metadata for a lambda expression?

like image 431
user1546077 Avatar asked Dec 21 '25 23:12

user1546077


1 Answers

I think you are talking about anonymous methods.So, you can write an extension method for that and check whether the name of the method contains any invalid chars.Because the compiler generated methods contain invalid chars, you can use that feature to determine whether the method is anonymous or not:

public static bool IsAnonymous(this MethodInfo method)
{
     var invalidChars = new[] {'<', '>'};
     return method.Name.Any(invalidChars.Contains);
}

Test:

Func<int> f = () => 23;

Console.Write(f.Method.IsAnonymous());  // true

More elegant way would be validating the method name using IsValidLanguageIndependentIdentifier method, like this (method from this answer):

public static bool IsAnonymous(this MethodInfo method)
{
    return !CodeGenerator.IsValidLanguageIndependentIdentifier(method.Name);
}

Remember in order to access IsValidLanguageIndependentIdentifier method you need to include the System.CodeDom.Compiler namespace.

like image 166
Selman Genç Avatar answered Dec 23 '25 13:12

Selman Genç



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!