locked
from an interface object, how get the class object that implements the interface? RRS feed

  • Question

  • I have an object that is an IEnumerable interface. How to use reflection to get the class object that the interface object is implemented from?

    In other words, if I know the ItemsSource of a ComboBox is a List<string> I can cast the interface object to the List<string> type:
       var itemsList = ComboBox1.itemsSource as List<string> ;

    But what if my code does not know that the ItemsSource IEnumerable is a List<string>? How to use reflection to find that out?

    thanks,

    Saturday, March 3, 2012 6:42 PM

Answers

  • Friend,
      You can get the actual type of the object in a variable using the GetType() method. Please try as below.

    var objType=myObject.GetType();//where myObject is your IEnumerable collection.


    -- Thanks Ajith R Nair

    • Proposed as answer by webJose Saturday, March 3, 2012 7:38 PM
    • Marked as answer by Steve Richter Saturday, March 3, 2012 8:45 PM
    Saturday, March 3, 2012 7:19 PM

All replies

  • Friend,
      You can get the actual type of the object in a variable using the GetType() method. Please try as below.

    var objType=myObject.GetType();//where myObject is your IEnumerable collection.


    -- Thanks Ajith R Nair

    • Proposed as answer by webJose Saturday, March 3, 2012 7:38 PM
    • Marked as answer by Steve Richter Saturday, March 3, 2012 8:45 PM
    Saturday, March 3, 2012 7:19 PM
  • Ajith shows you how you can easily get the object's type and most likely that answers your problem.  But just in case that doesn't really satisfy you, I present the "try to get what you need" approach:

    //I wish for my IEnumerable object to be of type List<string>.  Will I get my wish?
    List<string> wishCameTrue = myEnumerableObject as List<string>;
    if (wishCameTrue != null)
    {
        //Yay!!!  My wish came true!
    }
    else
    {
        //Bummer.  I didn't get what I wished for.
    }


    Jose R. MCP

    Saturday, March 3, 2012 7:38 PM
  •   You can get the actual type of the object in a variable using the GetType() method. Please try as below.

    var objType=myObject.GetType();//where myObject is your IEnumerable collection.

    heck, I had just assumed GetType would return the type of the interface.

    thank you very much,

    Saturday, March 3, 2012 8:45 PM