How can I achieve inheritance (or similar) with structs in C#? I know that an abstract struct isn\'t possible, but I need to achieve something similar.
I need it as
One under-appreciated feature of value types in .net is that they can be passed as interface-constrained generic types without boxing. For example:
T returnSmaller(ref T p1, ref T p2) where T:IComparable
{
return p1.CompareTo(p2) < 0 ? p1 : p2;
}
Note that I used ref
parameters to eliminate making extra temporary copies of the two parameters; an extra copy of p2
will end up being made when they are passed to the CompareTo
method, and at least one extra copy will likely be made when the result is returned, but making two redundant copies would be better than making four. In any case, the above method may be invoked without boxing on any type T
which implements IComparable
.
Unfortunately, there's no terribly nice way of saying "if T
is one type of struct, pass it to some method which takes that type; otherwise if it's some other type, pass it to a method and take that one". Thus, code which will require a specific exact class (like the code using the API's) will likely have to be non-generic. Nonetheless, if there are some methods which should be usable on a variety of structs, having those structs implement interfaces and then passing them as constrained generic types may offer some huge advantages.