Reputation: 2784
I have update function that I'd like to overload according to the input parameter (whether it is value type or reference type)
public void Update<T>(T item) where T : ValueType
the compiler has error and it insist I cannot use valuetype (and couple more as a constraint). should I give up or is there a neat way to overload method according to my desired types?
Upvotes: 1
Views: 112
Reputation: 1500275
You can use where T : struct
to enforce that T
is a non-nullable value type (this doesn't work with Nullable<T>
, despite that being a value type).
However, this won't help your bigger goal, as you can't overload by type constraints - so this is invalid:
// Invalid overloading
void Foo<T>(T item) where T : class
void Foo<T>(T item) where T : struct
Basically although the number of type parameters is part of the signature of the method (in terms of overloading), the names and constraints aren't.
There are horrible ways round this, but I'd recommend using different method names instead.
Upvotes: 1
Reputation: 10515
If you want a value type (non nullable), use a struct:
public void Update<T>(T item) where T : struct
Upvotes: 3