views:

200

answers:

4

I have a very thin interface that's going to define one method. Should I require the type parameter on the class definition?

public interface ISomethingFun<T>
{
    void Do(T item);
}

or method definition?

public interface ISomethingFun
{
    void Do<T>(T item);
}

What rationale? Is one easier to implement, inherit, or generate dynamically? Is it style? Is there some OO guidance that applies?

+1  A: 

The advantage to having the generic on the method is that it facilitates type inference.

void Example(ISomethingFun fun) {
  fun.Do(42);
}

There you go, a completely generic call, no generic parameters. Putting the generic Parameter on the type forces you to add generic signatures or bindings whenever the type is shown in metadata

void Example2<T>(ISomethingFun<T> fun) { ... }

This is not necessarily a bad thing and is in fact often necessary. It's just a difference.

In general though, if every method has the same generic parameter, just add it to the type :)

JaredPar
A: 

This is just my gut feeling, but since there's just one method, I'd put it on the method.

That way callers of Do<T> don't have to specify T explicitly.

SomethingFun fun = new SomethingFun();
fun.Do( DateTime.Now );
Greg
+1  A: 
  • Put it on the Class if the class deals with T's.
    • A Specific Example: A list of ints - you're searching for 42.
List<int> g;
g.Find(42);
  • Put it on the Method if the Class doesn't deal with T's but the Method does.
    • A Specific example: a list of objects, you're searching for an integer with a value of 42.
ArrayList g;
g.Find<int>(42)
Tom Ritter
+1  A: 

It should be on the interface.

The consumer of the interface should be able to constrain the type that Do expects. It can only do so by constraining the type of ISomethingFun. And the implementer should know what type to expect. If the generic parameter were on the method, then the implementer would have to handle any type, and the consumer would have no say.

Michael L Perry