tags:

views:

64

answers:

4

Is it possible to create a generic method with a signature like

public static string MyMethod<IMyTypeOfInterface>(object dataToPassToInterface)
{
    // an instance of IMyTypeOfInterface knows how to handle 
    // the data that is passed in
}

Would I have to create the Interface with (T)Activator.CreateInstance();?

+2  A: 

You can't instantiate interfaces. You can only instantiate classes that implement the interface.

Mark Byers
+1  A: 

You can constraint the type parameter to being something that implements IMyTypeOfInterface:

public static string MyMethod<T>(object dataToPassToInterface)
    where T : IMyTypeOfInterface
{
    // an instance of IMyTypeOfInterface knows how to handle 
    // the data that is passed in
}

However, you will never be able to "instantiate the interface".

Jørn Schou-Rode
+4  A: 

If you want to create a new instance of some type implementing the interface and pass some data you could do something like this:

public static string MyMethod<T>(object dataToPassToInterface) where T : IMyTypeOfInterface, new()
{
    T instance = new T();
    return instance.HandleData(dataToPassToInterface);
}

and call it like this:

string s = MyMethod<ClassImplementingIMyTypeOfInterface>(data);
Lee
A: 

You can't instantiate an interface, but you can ensure that the type passed as the generic parameter implements the interface:

    public static string MyMethod<T>(object dataToPassToInterface)
        where T : IMyTypeOfInterface
    {
        // an instance of IMyTypeOfInterface knows how to handle  
        // the data that is passed in 
    }
Scott J