To implement a generic interface in C#, follow these steps and see an example:
Step 1: Define the generic interface.
public interface IGenericInterface<T>
{
void PrintData(T data);
}
In this example, IGenericInterface is a generic interface with one method,
PrintData, that can work with a generic type T.
Step 2: Implement the generic interface in a class.
public class GenericClass<T> : IGenericInterface<T>
{
public void PrintData(T data)
{
Console.WriteLine($"Data: {data}");
}
}
Here, GenericClass is a class that implements the IGenericInterface using the same generic type
T. It provides an implementation for the PrintData method.
Step 3: Use the generic class.
class Program
{
static void Main()
{
IGenericInterface<int> intPrinter = new GenericClass<int>();
intPrinter.PrintData(42);
IGenericInterface<string> stringPrinter = new GenericClass<string>();
stringPrinter.PrintData("Hello, World!");
}
}
In this example, we create instances of the GenericClass for both
int and string types and use them to print data. The interface allows us to work with different data types in a generic manner.
This demonstrates how to implement a generic interface in C#. You can use the same interface with different data types, providing flexibility and reusability in your code.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
To implement a generic interface in C#, follow these steps and see an example:
Step 1: Define the generic interface.
In this example, IGenericInterface is a generic interface with one method, PrintData, that can work with a generic type T.
Step 2: Implement the generic interface in a class.
Here, GenericClass is a class that implements the IGenericInterface using the same generic type T. It provides an implementation for the PrintData method.
Step 3: Use the generic class.
In this example, we create instances of the GenericClass for both int and string types and use them to print data. The interface allows us to work with different data types in a generic manner.
This demonstrates how to implement a generic interface in C#. You can use the same interface with different data types, providing flexibility and reusability in your code.