Can’t go under it and can’t go over it

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;
  }
}

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
This entry was posted in Computers and Internet. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s