C
Join ServerC#
help
❔ How can I avoid supplying redundant generic type arguments in this case.
KKangarooChief1/24/2023
interface IDataStructure<ItemType, LocatorType> {...}
Class MyStringArray: IDataStructure<string, int> {...}
Class Effect<D, I, L> where D : IDataStructure<I,L> {...}
new Effect<MyStringArray, string, int>();
This is what I currently have. To give some context, I have a number of custom data structures (implementing IDataStructure) and I would like Effect to be a generic class that can operate on any of them. However, I need access to the Item and Locator types of the data structure within the Effect class.
The above code works however the I and L type arguments are essentially redundant since they can be inferred from D. I would like something like
class Effect<D<I,L>> where D : IDataStructure<I,L> { }
(which doesn't compile) so that I can do `new Effect<MyStringArray>()' (only specifying one generic type argument but having access to the Item and Locator types within the Effect class).WWindows10CE1/24/2023
the way to do this while preserving the types and without the repeated generic would be associated types, but those don't exist in C# yet
WWindows10CE1/24/2023
if you're okay with the types being erased and with some boxing, you can have a non-generic version of
IDataStructure<I, L>
that exposes the same properties as object
s, then constrain to that interface insteadWWindows10CE1/24/2023
otherwise you just have to keep the generics I think
KKangarooChief1/24/2023
Thanks 👍
AAccord1/25/2023
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.