C#C
C#3y ago
Loup&Snoop

✅ Refering to Generic Base Class

struct MyStruct1 : IStruct
struct MyStruct2 : IStruct

abstract class MyBaseClass<TStruct> where TStruct : IStruct {
TStruct storedVar;
public void Foo(TStruct x) { storedVar = x; }
[many methods to be inherited. None have TStruct arguments. Some use storedVar.]
}

class MyClass1 : MyBaseClass<MyStruct1> {
1-3 unique methods specifically needing MyStruct1 }

class MyClass2 : MyBaseClass<MyStruct2> {
1-3 unique methods specifically needing MyStruct2 }

-
I want to:
1) Avoid boxing with storedVar
2) I want to be able to make collections that can hold a mixture of the derived types, and call the abstract BaseClass methods without downcasting.

So far, I have been using an interface to tack on to MyBaseClass, but it seems like a very hacky solution, and forces some property getters to be public (that I would rather be protected).

Any suggestions on how to do this? I think an abstract nongeneric base class (for generic base class to derive from) is the answer, but I don’t know how to avoid boxing storedVar as an Istruct if I do that.
Was this page helpful?