Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to access an object's property through its interface in C#

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading