Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Generic Generics (A Serious Question)

In C# I am trying to write code where I would be creating a Func delegate which is in itself generic. For example the following (non-Generic) delegate is returning an arbitrary string:

Func<string> getString = () => "Hello!";

I on the other hand want to create a generic which acts similarly to generic methods. For example if I want a generic Func to return default(T) for a type T. I would imagine that I write code as follows:

Func<T><T> getDefaultObject = <T>() => default(T);

Then I would use it as

getDefaultObject<string>() which would return null and if I were to write getDefaultObject<int>() would return 0.

This question is not merely an academic excercise. I have found numerous places where I could have used this but I cannot get the syntax right. Is this possible? Are there any libraries which provide this sort of functionality?

like image 539
Tahir Hassan Avatar asked May 24 '10 14:05

Tahir Hassan


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr. Stroustroupe.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

Is C programming hard?

C is more difficult to learn than JavaScript, but it's a valuable skill to have because most programming languages are actually implemented in C. This is because C is a “machine-level” language. So learning it will teach you how a computer works and will actually make learning new languages in the future easier.


1 Answers

Well you can't overload anything based only on the return value, so this includes variables.

You can however get rid of that lambda expression and write a real function:

T getDefaultObject<T>() { return default(T); }

and then you call it exactly like you want:

int i=getDefaultObject<int>();       // i=0
string s=getDefaultObject<string>(); // s=null
like image 53
Blindy Avatar answered Sep 20 '22 15:09

Blindy