Get implementation out of list of interfaces without explicit casting
Merry Christmas!
Trying to get the instance implementation out of a list of an interface, without explicitly casting the item of the list to the desired class, as per
https://sharplab.io/#v2:CYLg1APgAgTAjAWAFBQAwAIpwCwG5nIAyAlgM4AuAPAJIBiA9vQHzoA2Z56AvOgHYCmAdwAUASmQBvZOhl8h6AIJiANHMHoAQmOQBffEmQB6Q+gAqACzLorAM2IDkAYXq9S9VvwB0AdQBOxcn5hdgoAbVQAXU8AcX5yaldyAENeAGN+SgUmMU8AZXoAW35RfSwATmCOULgo2PjElPTKDWzRTwt7AHMSgiRjTQBXTkF6AdZgdF8k8nN+X3QkqGx0UgAHflTiGwBPLvQZ/n3t9ZX6fctSdFT6YEORsYnyAd9edAA3JPZgIxMQ8nDanEEhRGkE2vkij82FUajEgQ00mD2pZeJ1erBFOgQOg6IxJNJZFAAMyYOAYCGHLgsABEFOp+gJMlMOIY9Dh9RBiMopla3BYMzI+h06JgmixLLxSCkSFkmBJWAwHVRfPQ1IFqPpvVlzNxbLqwOSXJ5YhVAtIQt69kCvhsSXSEvo+JlsmZ+oRTWNonQglmvkOzOxsAtSCAA==
This gives the wanted output however it misses the casting point
https://sharplab.io/#v2:C4LgTgrgdgNAJiA1AHwAICYCMBYAUKgBgAJVMAWAbjzwBkBLAZ2AB4BJAMQHtOA+IgG0bAiAXiJQApgHcAFAEo8AbzxFV46UQCC8mOqlEAQvLwBfKrjwBhTlAad+EgHQB1MHWASZMwUwDaBAF0iAEMGLTkAQkcAZU4AWwk5c1IATi8fYF9MINDDSMcAFQALOigAcyTqfHQtIhAiDm4lFTVUAGYSTGJYhNE+ACIeiX7zEyqMQzqGrk5m3DUSDtJiYtKyvqJ+4BLykdMq0o8wADNggGMJaabcZVwTIA===
The questions are:
How do you implicitly convert class A and B to generic T?
Is there another way to represent a list that can contain multiple implementations? If so then may you show a snippet, reference to some article/keyword or query to google?
2 Replies
You're not going to like the answers to your questions
First: you cannot convert
this
to T
implicitly. It's the definition of unsafe
Did you perhaps want to specify IFoo
as IFoo<T> where T : IFoo<T>
, and then have A
implement IFoo<A>
?
And not have GetInstance
be generic at all?
Note that, of course, that would mean that you can't specify List<IFoo>
, because you don't have a concrete type argument
A list of heterogeneous data needs to be checked when trying to access individual elements as specific subtypes of that data
You have no way of knowing, given a List<IFoo>
, which elements are actually A
s and which are B
s, and yes you will need to do type tests or specify the type in some fashion to access members specific to A
or B
on each elementGotcha, thanks for the explanation!