I expect an overload is your best option here:
string Add(object value, MyStruct1 expiration) {...}
string Add(object value, MyStruct2 expiration) {...}
This is even more appropriate since you can't subclass a struct, thus the only viable T
in your example would be MyStruct1
and MyStruct2
- may as well have specific methods, then.
Re restricting generics to multiple cited types; not really - and even if there were, the name "Add" suggests you'd want to use operator support, which also isn't in C# (3.0).
However, in C# 4.0, dynamic
might be an option here - this acts as an optimised form of duck-typing; you wouldn't get compiler support (validation etc), but it should work. You would cast to dynamic
inside the method:
string Add<T>(object value, T expiration) where T : struct {
dynamic valueDyn = value;
valueDyn += expiration; // or similar
// more code
}
Another option (in .NET 3.5) is to use the Operator
support in MiscUtil, using Operator.Add
or Operator.AddAlternative
.