Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to define a generic lambda in C#?

Tags:

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.

like image 783
hcoverlambda Avatar asked Mar 08 '10 21:03

hcoverlambda


People also ask

Can lambda expressions be generic?

A lambda expression can't specify type parameters, so it's not generic. However, a functional interface associated with lambda expression is generic.

Is there lambda in C?

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.

How do you define a lambda function in C++?

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.

How is lambda defined?

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.


2 Answers

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>();      // ... } 
like image 70
ZaldronGG Avatar answered Oct 02 '22 22:10

ZaldronGG


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.

like image 35
JaredPar Avatar answered Oct 02 '22 21:10

JaredPar