You are not making type inference in the class statement, you are making it in the variables statement when you instantiate the class. You’re just using a generic type in class.
What you want is a standard argument in the generic type, so when instantiating the class that requires you to be informed which type for the class to be created you don’t have to say which is the type, because after all, probably almost all cases are the same type to be used, exemplified string
. It makes sense to want this, but unlike C++, C# doesn’t have this and is not expected to be so soon (but you can ask), will have to do in hand. But let’s face it, it’s not the end of the world. If I allowed it, it would be 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; }
}
Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.
It’s 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 don’t think it’s cool to create a hierarchy to facilitate typing instead of doing it to better model the problem, Seems like abuse of the mechanism, even if it works. Even the using
, which does not pose serious problems other than a reduction in readability, is only used in complex cases.
I answered now. I think you can solve your implementation. Look there.
– Sergio Cabral