Alex Rivera | Logout

Anyway to default a generic parameter to a certain type?

Asked 2010-11-08T20:42:34.453
22

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!

Edit
Report

3 Answers

34

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>.

answered 2010-11-08T20:56:04.633
2

You can use the where keyword to constrain the specific types that can be used as type parameters.

For example, you could your class to only accept generic type parameters where the type implements the IComparable interface:

class Something<T> where T : IComparable
{
}

Or, as you mentioned, you can constrain T to be a value type by using where T : struct:

class Something<T> where T : struct
{
}

See MSDN's article on Constraints on Type Parameters for more info. Hope this helps!

answered 2010-11-08T20:45:16.433
2

I don't believe there is a way to default it to a certain type, but you could put that as a comment in the XML docs. As far as restricting to a value type, you can obtain this behavior by declaring your generic as follows:

class MyGeneric<T> where T : struct
{
    ...
}
answered 2010-11-08T20:47:43.123

Your Answer