I have some logic in a method that operates on a specified type and I'd like to create a generic lambda that encapsulates the logic. This is the spirit of what I'm trying to do:
public void DoSomething() { // ... Func<T> GetTypeName = () => T.GetType().Name; GetTypeName<string>(); GetTypeName<DateTime>(); GetTypeName<int>(); // ... }
I know I can pass the type as a parameter or create a generic method. But I'm interested to know if a lambda can define its own generic parameters. (So I'm not looking for alternatives.) From what I can tell, C# 3.0 doesn't support this.
A lambda expression can't specify type parameters, so it's not generic. However, a functional interface associated with lambda expression is generic.
the C standard does not define lambdas at all but the implementations can add extensions. Gcc also added an extension in order for the programming languages that support lambdas with static scope to be able to convert them easily toward C and compile closures directly.
A lambda can introduce new variables in its body (in C++14), and it can also access, or capture, variables from the surrounding scope. A lambda begins with the capture clause. It specifies which variables are captured, and whether the capture is by value or by reference.
Lambda, the 11th letter of the Greek alphabet, is the symbol for wavelength. In optical fiber networking, the word lambda is used to refer to an individual optical wavelength.
While Jared Parson's answer is historically correct (2010!), this question is the first hit in Google if you search for "generic lambda C#". While there is no syntax for lambdas to accept additional generic arguments, you can now use local (generic) functions to achieve the same result. As they capture context, they're pretty much what you're looking for.
public void DoSomething() { // ... string GetTypeName<T>() => typeof(T).GetType().Name; string nameOfString = GetTypeName<string>(); string nameOfDT = GetTypeName<DateTime>(); string nameOfInt = GetTypeName<int>(); // ... }
It is not possible to create a lambda expression which has new generic parameters. You can re-use generic parameters on the containing methods or types but not create new ones.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With