I have a class A with a property A.A and a class B with a property B.B. Both implement the IC interface that defines the IC.C property, but do not defines A.A or B.B.
I want a method that receive an instance of A or B as a parameter and can access those properties, something like:
void MyMethod(IC obj)
{
if (obj.GetType().Name.Equals("A"))
{
var v = obj.A; // some code for access A
}
}
Is that possible? And, is it a good idea? Thanks!
Edited: renaming the interface as IC as suggested by @dmedine.
CodePudding user response:
The best approach would depend on the specifics of what you are trying to do, but here are 2 options:
Pattern matching
void MyMethod(C obj)
{
if (obj is A objAsA)
{
var vA = objAsA.A;
}
if (obj is B objAsB)
{
var vB = objAsB.B;
}
}
Reflection
void MyMethod(C obj)
{
var objType = obj.GetType();
if (objType.Name.Equals("A"))
{
var prop = objType.GetProperty("A");
var v = prop.GetValue(obj, null);
}
}
CodePudding user response:
Doing this can, in my opinion, be useful under certain circumstances. For instance, if you have a bunch of objects that inherit from interface IC
(always start the name of an interface with I) that have similar but also unique properties/methods (can't wait for the comments to roll in). You can test the type of class that inherits using is
. For example, assuming A
and B
implement IC
:
void MyMethod(List<IC> objects)
{
foreach(IC object in objects)
{
var cProperty = object.CProperty; // use common property
if(object is A a)
var aProperty = a.AProperty; // if A, use unique property
}
}
void Foo()
{
List<IC> cObjects = new();
cObjects.Add(new A());
cObjects.Add(new B());
MyMethod(cObjects);
}