Wednesday, October 19, 2016

casting fails!

Consider the following C# classes:

  1. namespace Something.Models
    {
       public class Cat
       {
          public int Lives { get; set; }
          
          public Cat()
          {
             Lives = 9;
          }
       }
    }
     
  2. namespace Something.Models
    {
       public class BakersCat : Cat
       {
          public BakersCat()
          {
             Lives = 13;
          }
       }
    }
     
  3. using Something.Models;
    namespace Something.Utilities
    {
       public static class Killer
       {
          public static Cat Kill(Cat cat)
          {
             cat.Lives = cat.Lives - 1;
             return cat;
          }
          
          public static void Kill(ref Cat cat)
          {
             cat.Lives = cat.Lives - 1;
          }
       }
    }

 
 

Well this won't work...

BakersCat muffin = new BakersCat();
muffin = Killer.Kill(muffin);

 
 

...and this won't work either!

BakersCat cookie = new BakersCat();
Killer.Kill(ref cookie);

No comments:

Post a Comment