Reading source code should be the aim of every serious software developer. I am constantly looking for patterns that are interesting and potentially useful for future projects. Anyway, I was reviewing some code over the weekend and there was a pattern that I have not seen for a while.

So below is a basic abstract Mammal class, you have two constructors differentiated by the method signature (of course).

public abstract class Mammal
{
	public Mammal()
	{
		Console.WriteLine("A");
	}
	public Mammal(bool asf)
	{
		Console.WriteLine("B");
	}
}

So the MyDog class inherits from from Mammal and provides an opportunity to access the either of the base class constructors.

public class MyDog : Mammal
{
	public MyDog() : base()
	{
		Console.WriteLine("1");
	}
	public MyDog(bool asf) : base(asf)
	{
		Console.WriteLine("2");
	}
}

You can explicitly select which base class constructor gets called by using ": base()" pattern after the constructor. Simple but nice!

Technorati tags: ,

Share on Twitter Facebook

Comment Section

Comments are closed.