Reputation: 8562
I have several classes that implement IMyInterface. The interface contains a method called Delete, so all classes define their own Delete method.
I also have a lot of spots in my code where I’m calling MyClass1.Delete(myClass1Id) or MyClass2.Delete(myClass2Id), etc.
I’m trying to define a generic, common method that takes a generic class parameter and a string for the Id.
I’m guessing it would look something like this, but I can’t find any relevant documentation on using generic classes in this fashion:
public static void DeleteGeneric<TMyClass>(string myId)
{
//call the relevant Delete method for the TMyClass class
}
Upvotes: 0
Views: 64
Reputation: 748
I think you want code like this:
public static void DeleteGeneric<TMyClass>(TMyClass myId) where TMyClass : IMyInterface
{
myId.Delete();
}
That says that TMyClass has to implement the IMyInterface interface and the parameter passed is of whatever type TMyClass is.
It might be simpler without generics
public static void DeleteGeneric(IMyInterface myId)
{
myId.Delete();
}
Disclaimer, I typed this code into the browser so there maybe syntax errors.
Upvotes: 1
Reputation: 203836
There's no need to use generics here at all; just accept an instance of the interface:
public static void DeleteGeneric(IMyInterface deletable, string myId)
{
deletable.Delete(myId);
}
Upvotes: 3