Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Generics, Constrain to Specific Structs

Is it possible to constrain a genericised method to accept only specific types of struct?

This is OK I believe:

string Add<T>(object value, T expiration) where T : struct; 

but this isn't it appears:

string Add<T>(object value, T expiration) where T : Struct1, Struct2; 

Note: the structs I wish to constrain it to are DateTime or TimeSpan and hence I have no control over them.

Thanks

like image 403
Ben Aston Avatar asked Nov 29 '09 11:11

Ben Aston


2 Answers

No, as a struct is sealed (you can't create a subclass of a ValueType).

Instead, consider having your structs implement an interface, then use that as a constraint, like so:

string Add<T>(object value, T expiration) where T : struct, IMyInterface

like image 116
Jeremy McGee Avatar answered Oct 21 '22 08:10

Jeremy McGee


The purpose of generics is to make methods and types that are generic, hence the name. If you only have two possible type arguments, then just write two methods.

Remember also, C# generics are not C++ templates. When you call a method on a type parameter, say, that method call will be the exact same method call for every construction of the type parameter. It's generic. It's not a template where the compiler compiles the code two, three, a thousand times, one for each type argument, and works out afresh for each one what the method call is.

So even if you could restrict your type argument to two types, what good would that do you? All you could call on them was the methods they had in common via their base class, Object. In which case, you've got a generic method that works on all objects, so why restrict it to two types?

like image 32
Eric Lippert Avatar answered Oct 21 '22 10:10

Eric Lippert