Demystifying C# Generics
AramT
88.9K views
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
This is similar to generic classes, you define a parameter T on the interface level, and your methods can use this parameter in their prototype, so any class that will be implementing this interface will naturally implement the parameter T within its own methods. You can also add constraints to generic interfaces. Note that the class which will be implementing the generic interface must define the parameter T.
To test the above implementation, we will be creating an object from Book with parameter String, and then we will use the add method to add the string value to the Book class.
The example below will illustrate the use of a generic interface:
The below code shows you how you can create a generic interface
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
namespace GenericsLesson
{
class Book<T> : IBook<T>
{
T book;
public void add(T book)
{
this.book = book;
}
public void delete()
{
this.book = default(T);
}
public T get()
{
return this.book;
}
}
}
Enter to Rename, Shift+Enter to Preview
1
namespace GenericsLesson
Enter to Rename, Shift+Enter to Preview
1
using Microsoft.VisualStudio.TestTools.UnitTesting;
Enter to Rename, Shift+Enter to Preview
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content