Why can't the compiler output type arguments in the first example?
Type inference uses method arguments to output type arguments. In the first example, there are no method arguments that can be used to output a type argument.
Why does it work when called using the extension method?
The extension method is actually a static method, and the object that you "extend" is passed as an argument to the extension method:
Extensions.WithAttributesEx<T>(d, "one", "two")
As stated above, type inference uses method arguments to search for type arguments. Here, the type argument can be inferred from the argument type of the first method, which is Derived .
Is there a way to make it work as a class-based instance method without explicitly specifying a type argument?
Make the base class general and parameterize it with the derived class (called a curiously repeating template pattern ):
public class Base<T> where T : Base<T> { private List<string> attributes = new List<string>(); public T WithAttributes(params string[] attributes) { this.attributes.AddRange(attributes); return this as T; } } public class Derived : Base<Derived> { }
Using:
Derived d = new Derived().WithAttributes("one", "two").WithAttributes("three");
source share