C
C#15mo 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.
3 Replies
reflectronic
reflectronic15mo ago
the only way to have something like List<MyBaseClass> at the moment is to use an abstract base class or interface if you don't want the boxing then you can't have the field in the abstract base class. at which point, it is basically an interface
reflectronic
reflectronic15mo ago
you may be interested in this language proposal https://github.com/dotnet/csharplang/issues/5556
GitHub
[Proposal]: Practical existential types for interfaces · Issue #555...
Practical existential types for interfaces Proposed Prototype: Not Started Implementation: Not Started Specification: Not Started Intro Previously I proposed adding some form of existential types t...
Loup&Snoop
Loup&SnoopOP15mo ago
Thanks. I think this helps. It seems like a big hacky interface is going to be the solution, unfortunately.

Did you find this page helpful?