Thursday, January 31, 2013

The parameterless constructor on a base class is always called when a child's constructor is called in C#.

Something interesting is to come, but first, look at this:

using System;
namespace ParameterlessConstructorExample.Models
{
   public class Animal
   {
      public Int32 numberOfMouths { get; set; }
      
      public Animal()
      {
         numberOfMouths = 1;
      }
   }
}

 
 

Now for something interesting: If Bird inheirts from Animal, then newing up a Bird will cause the parameterless constructor on Animal to be called.

using System;
namespace ParameterlessConstructorExample.Models
{
   public class Bird : Animal
   {
      public Int32 numberOfLegs { get; set; }
      
      public Bird()
      {
         numberOfLegs = 2;
      }
   }
}

 
 

ViewBag.Whatever below will end up with the number one in it.

using System.Web.Mvc;
using ParameterlessConstructorExample.Models;
namespace ParameterlessConstructorExample.Controllers
{
   public class HomeController : Controller
   {
      public ActionResult Index()
      {
         Bird bird = new Bird();
         ViewBag.Whatever = bird.numberOfMouths;
         return View();
      }
   }
}

 
 

This comes from chapter 18 of C# in a Nutshell. I tried to find a way to set numberOfLegs in Animal and have the Animal setting sabotage the Bird's setting, but fortunately there isn't an easy way to "accidentally" do this. I found this which made me smile. The first bullet of the Conclusion is: "C# is not Java."

No comments:

Post a Comment