There’s a great trick in Real World Functional Programming for getting construction of generic classes to work without the need for explicitly giving the types. If we have a class like the following:
class MyType<TX, TY>
{
TX m_X;
TY m_Y;
public MyType(TX x, TY y)
{
m_X = x;
m_Y = y;
}
}
{
static public MyType<TX, TY> Create<TX, TY>(TX x, TY y)
{
return new MyType<TX, TY>(x, y);
}
}
{
TX m_X;
TY m_Y;
public MyType(TX x, TY y)
{
m_X = x;
m_Y = y;
}
}
we’d like to be able to use it to assign a new instance to a variable that is implicitly typed. However,
var x = new MyType(2, "hello");
fails as C# requires that the generic type arguments are provided.
C# does allow the inference of types at the callsite of a generic method. Hence the trick is to define such a method, in say a static class.
static class MyType{
static public MyType<TX, TY> Create<TX, TY>(TX x, TY y)
{
return new MyType<TX, TY>(x, y);
}
}
which we can then use in code like the following
var x = MyType.Create(2, "hello");
and hence avoid needing to give the types explicitly.
Advertisements