Advantages of using generic interfaces.
- Compile – time safety.
- Much less boxing
- Backward compatibility with non-generic interfaces.
- Availability to implement generic interface several times, as long as different type parameters are used.
Example 1.1:
class CompileTimeSafetyTest : IComparable
{
int x = 0;
public int CompareTo(object param)
{
return x.CompareTo(param);
}
}
class Program
{
static void Main(string[] args)
{
CompileTimeSafetyTest ctsTest = new CompileTimeSafetyTest();
ctsTest.CompareTo(2);
//Run-time error. Object must be of an Int32 type.
ctsTest.CompareTo("2");
}
}
Example 1.2:
class CompileTimeSafetyTest : IComparable<int>
{
int x = 0;
public int CompareTo(int param)
{
return x.CompareTo(param);
}
}
class Program
{
static void Main(string[] args)
{
CompileTimeSafetyTest ctsTest = new CompileTimeSafetyTest();
ctsTest.CompareTo(2);
//Compile-time error. Cannot convert from ‘string’ to ‘int’.
ctsTest.CompareTo("2");
}
}
1. As we can see from the examples above generic interface provides compile type safety.
2. The second benefit of generic interfaces is much less boxing will occur when we working with value types.
Example 2:
class CompileTimeSafetyTest : IComparable, IComparable<int>, IComparable<string>
{
int x = 0;
string s = "test";
public int CompareTo(object param)
{
throw new ArgumentException("Can’t compare your type");
}
public int CompareTo(int param)
{
IComparable<int> compInt = x;
return compInt.CompareTo(param);
}
public int CompareTo(string param)
{
IComparable<string> compString = s;
return compString.CompareTo(param);
}
}
3. For the backward compatibility we must implement non-generic version of an interface as well.
4. The forth benefit is that we can implement the same generic interface multiple times as long as different type parameters are used.