You are not making type inference in the class declaration, you are doing in the declaration of variables when you instantiate the class. You are only using a generic type in the class.
What you want is a default argument in the generic type, so when instantiating the class that requires you to be told which type to create the class does not need to say what type it is, because after all, probably almost every case is the same type to be used, exemplified string
. It makes sense to want this, but unlike C ++, C # does not have this and has no forecast to have it so early (but you can request ), will have to do in hand. But let's face it, it's not the end of the world. If it were allowed, it would look something like this:
public class Foo<T = string> {
public T Bar { get; set; }
}
There are some cases that a generic method may have the type inferred by the argument used within it, but it is not what you want.
You can create an alias with using
and avoid full use:
using Foo = Foo<string>;
public class Program {
public static void Main() {
var a = new Foo<int>();
var b = new Foo();
}
}
public class Foo<T> {
public T Bar { get; set; }
}
See running on .NET Fiddle . And no Coding Ground . Also put it in GitHub for future reference .
It is also possible to create a class that encapsulates this as shown in the other answers, but this can be problematic for a very small gain, I do not think it's cool to create a hierarchy to make it easier to type rather than to model the problem better. seems to abuse the mechanism, even if it works. Even using
, which does not cause serious problems other than a reduction in legibility, is only used in complex cases.