views:

295

answers:

4

How to get generic interface type for an instance ?

Suppose this code:

interface IMyInterface<T>
{
    T MyProperty { get; set; }
}
class MyClass : IMyInterface<int> 
{
    #region IMyInterface<T> Members
    public int MyProperty
    {
        get;
        set;
    }
    #endregion
}


MyClass myClass = new MyClass();

/* returns the interface */
Type[] myinterfaces = myClass.GetType().GetInterfaces();

/* returns null */
Type myinterface = myClass.GetType().GetInterface(typeof(IMyInterface<int>).FullName);
A: 
MyClass myc = new MyClass();

if (myc is MyInterface)
{
    // it does
}

or

MyInterface myi = MyClass as IMyInterface;
if (myi != null) 
{
   //... it does
}
thelost
But I need the type, because I'm adding it to a Collection.
PaN1C_Showt1Me
+2  A: 

In order to get the generic interface you need to use the Name property instead of the FullName property:

MyClass myClass = new MyClass();
Type myinterface = myClass.GetType()
                          .GetInterface(typeof(IMyInterface<int>).Name);

Assert.That(myinterface, Is.Not.Null);
Elisha
A: 

Use Name instead of FullName

Type myinterface = myClass.GetType().GetInterface(typeof(IMyInterface).Name);

Andrei Taptunov
A: 

Why you dont use "is" statement? Test this:

class Program
    {
        static void Main(string[] args)
        {
            TestClass t = new TestClass();
            Console.WriteLine(t is TestGeneric<int>);
            Console.WriteLine(t is TestGeneric<double>);
            Console.ReadKey();
        }
    }

interface TestGeneric<T>
    {
        T myProperty { get; set; }
    }

    class TestClass : TestGeneric<int>
    {
        #region TestGeneric<int> Members

        public int myProperty
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        #endregion
    }
Stremlenye