Friday, April 24, 2015

Did you know you may get freaky in speaking from a child's constructor to a parent's constructor in C#?

It doesn't have to be a one-to-one pass-right-though type of mapping. If we have a parent like so...

namespace Cats.Models
{
   public class Feline
   {
      public string Speak { get; private set; }
      public Feline(string meow)
      {
         Speak = meow;
      }
   }
}

 
 

...there is plenty of room for dress up on the child's part.

namespace Cats.Models
{
   public class Panther : Feline
   {
      public Panther(string roar) : base(roar.ToUpper() + "!!!")
      {
      }
   }
}

 
 

You may also call out to static methods in static classes to undertake more complicated surgical procedures, allowing what goes into the base constructor to be maintained as a single line of code, or really less than a single line of code, just variables, you know?

No comments:

Post a Comment