Thursday, April 23, 2015

Generic Type Parameters in C#

Generic type parameters are used all over the place in built-in constructs in C#, such as
   1:  IEnumerable<T>
and
   1:  List<T>
which you've probably used before.

But you can create your own methods to use generic type parameters, too.  You may be asking why you'd want to do this.  Well, the short answer is compile-time support for methods that return an instance of an object only known at runtime.  That's one reason anyway, and it's the reason I'll demonstrate here.

Let's say you have two classes:

   1:  public class ClassOne
   2:  {
   3:      public string FirstName { get; set; }
   4:  }
   5:   
   6:  public class ClassTwo
   7:  {
   8:      public int Id { get; set; }
   9:  }

And a method that can return an instance of either class:

   1:  public ClassOne | ClassTwo BuildAnObject()
   2:  {
   3:  }

(Hint: that won't compile)

So if you know that your method will return one or the other, you could write two separate methods, taking the exact same parameters, but returning a different type.  That would technically work (if you named the methods differently anyway), but it's kind of a pain in the butt.  Instead, you can change your method signature to use generic type parameters to specify the return type when you call the method:


   1:  public T BuildAnObject<T>()
   2:  {
   3:      return default(T);
   4:  }

At this point, "T" represents whatever you want it to represent.  This way, if you created a third class you could use the exact same method by specifying ClassThree as T when you make the call:

   1:  public void BuildIt()
   2:  {
   3:      var result = BuildAnObject<ClassOne>();
   4:   
   5:      var firstName = result.FirstName;
   6:  }

Right there you can see we have compile-time support for result.

No comments:

Post a Comment