Sunday, September 22, 2013

"upcast" to dynamic

Going through this a smidge more, I find I want to offer an easier example of casting to dynamic than what I offered here. Observe:

namespace Whatever.Whatever
{
   public static class TortureChamber
   {
      public static string GetScreams(dynamic guest)
      {
         return guest.Scream();
      }
   }
}

 
 

We may use our TortureChamber by handing in any object that has a public (or perhaps internal) Scream method on it, such as a Clown:

namespace Whatever.Whatever
{
   public class Clown
   {
      public string Scream()
      {
         return "Honk! Honk! Honk!";
      }
   }
}

 
 

If we do something like this...

Clown clown = new Clown();
string result = TortureChamber.GetScreams(clown);

 
 

The result variable is going to end up with "Honk! Honk! Honk!" in it. The runtime process will try at runtime to find a Scream method upon the dynamic object given our code in TortureChamber, but not until that method is called. If the public (or perhaps internal) Scream method is not there on the type cast to dynamic at the method signature, then the compiler will nonetheless not "know" to complain about it. The harsh reality of the missing method won't be exposed until runtime. There is no compiler safety. That is what dynamic is all about! An example of a runtime error might be:

'Whatever.Whatever.Mime' does not contain a definition for 'Scream'

 
 

This happens at runtime if Mime has no public (or perhaps internal) Scream method like so:

namespace Whatever.Whatever
{
   public class Mime
   {
   }
}

 
 

This would cause the error:

Mime mime = new Mime();
string result = TortureChamber.GetScreams(mime);

No comments:

Post a Comment