Wednesday, February 13, 2013

use dynamic to add nonspecific types in C# 4.0

I'm getting into the 4.0 part of C# 4.0 in a Nutshell (a book I'm reading), and I don't mean Tuples. I mean dynamic! I didn't see what was so special about dynamic below until I tried to somehow strip it out. There is no way else to do the addition of two instances of T.

namespace Whatever.Objects
{
   public static class Adder
   {
      public static T Add<T> (T originalValue, T addendum)
      {
         dynamic combo = (dynamic) originalValue + addendum;
         return (T) combo;
      }
   }
}

 
 

If we use the static method like so...

int foo = 13;
int bar = 42;
string baz = "hello";
string qux = "world";
int sum = Adder.Add(foo, bar);
string concatenation = Adder.Add(baz, qux);
DateTime timeToFreakOut = Adder.Add(baz, qux);

 
 

...then we should expect...

  1. sum would end up with 55 inside of it if this code could compile
  2. concatenation would end up with helloworld inside of it if this code could compile
  3. timeToFreakOut makes it so the code cannot compile as the type to assign to is not consistent with the types handed in

No comments:

Post a Comment