Reputation: 42175
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
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
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
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
Reputation: 838126
You can't instantiate interfaces. You can only instantiate classes that implement the interface.
Upvotes: 2