Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anyway to default a generic parameter to a certain type?

Tags:

Is there a way to provide a default type for a parameter T of a generic, something like:

class Something<T = string> { } 

I know there aren't many strong reasons for this, but I would like to hint the code client which type he should be preferably using.

Another thing, can I restrict the generic type to a ValueType? I've just seen that you can't, but still, I'd like to know why. Anyone has a clue?

Thanks!

like image 683
Bruno Brant Avatar asked Nov 08 '10 20:11

Bruno Brant


People also ask

Is it possible to inherit from a generic type?

You can't inherit from the generic type parameter. C# generics are very different from C++ templates. Inheriting from the type parameter requires the class to have a completely different representation based on the type parameter, which is not what happens with .

How do you indicate that a class has a generic type parameter?

A generic type is declared by specifying a type parameter in an angle brackets after a type name, e.g. TypeName<T> where T is a type parameter.

Is generic type parameter?

Generic MethodsA type parameter, also known as a type variable, is an identifier that specifies a generic type name. The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type arguments.

What is generic type constraint?

The where clause in a generic definition specifies constraints on the types that are used as arguments for type parameters in a generic type, method, delegate, or local function. Constraints can specify interfaces, base classes, or require a generic type to be a reference, value, or unmanaged type.


1 Answers

Ok, I suppose you have the class:

class Something<T> {  } 

Now, you might want another class:

class Something : Something<string> {     // NO MORE CODE NEEDED HERE! } 

This is the only and the best way.
So if one uses Something he will actually use Something<string>.

like image 84
Vercas Avatar answered Oct 04 '22 03:10

Vercas