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.
>Solution :
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);
}
}