Understanding Interface-Based Programming (Page 1 of 5 )
In this final part of a four-part series focused on interface-based programming, you'll learn about interface factoring, factoring metrics, and more. This article is excerpted from chapter three of
Programming .NET Components, Second Edition, written by Juval Lowy (O'Reilly, 2006; ISBN: 0596007620). Copyright © 2006 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.
Generic Interface Methods
In C# 2.0, an interface method can define generic type parameters, specific to its execution scope:
public interface IMyInterface<T>
{
void MyMethod<X>(T t,X x);
}
This is an important capability, because it allows you to call the method with a different type every time, which is often very handy for utility classes.
You can define method-specific generic type parameters even if the containing interface does not use generics at all:
public interface IMyInterface
{
void MyMethod<T>(T t);
}
This ability is for methods only. Properties or indexers can use only generic type parameters defined at the scope of the interface.
When you call an interface method that defines generic type parameters, you can provide the type to use at the call site:
public class MyClass : IMyInterface
{
public void MyMethod<T>(T t)
{...}
}
IMyInterface obj = new MyClass();
obj.MyMethod<int>(3);
That said, when the method is invoked, the C# compiler is smart enough to infer the correct type based on the type of parameter passed in, and it allows you to omit the type specification altogether:
IMyInterface obj = new MyClass();
obj.MyMethod(3);
This ability is called generic type inference. Note that the compiler cannot infer the type based on the type of the returned value alone:
public interface IMyInterface
{
T MyMethod<T>();
}
public class MyClass : IMyInterface
{
public T MyMethod<T>()
{...}
}
IMyInterface obj = new MyClass();
int number = obj.MyMethod();//Does not compile
When an interface method defines its own generic type parameters, it can also define constraints for these types:
public interface IMyInterface
{
void MyMethod<T>(T t) where T : IComparable<T>;
}
However, my recommendation to avoid constraints at the interface level extends to method-level generic type parameters as well.
Next: Designing and Factoring Interfaces >>
More .NET Articles
More By O'Reilly Media
|
This article is excerpted from chapter three of Programming .NET Components, Second Edition, written by Juval Lowy (O'Reilly, 2006; ISBN: 0596007620). Check it out today at your favorite bookstore. Buy this book now.
|
|