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 I've just seen that you can't, but still, I'd like to know why. Anyone has a clue?ValueType
?
Thanks!
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 .
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.
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.
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.
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>
.
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