DaveDev
DaveDev

Reputation: 42175

Can I Create A Generic Method of a Type of Interface?

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();?

Upvotes: 0

Views: 233

Answers (4)

Scott J
Scott J

Reputation: 1331

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 
    }

Upvotes: 0

Lee
Lee

Reputation: 144136

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);

Upvotes: 5

J&#248;rn Schou-Rode
J&#248;rn Schou-Rode

Reputation: 38346

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".

Upvotes: 1

Mark Byers
Mark Byers

Reputation: 838126

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

Upvotes: 2

Related Questions