Thursday 9 March 2017

Sharing a signature between constructors

Let's say that you need multiple constructors however they would all require the same signature; well even a novice developer knows this can't be done (yes the tile of this post is misleading), however a neat little work around is just to create static methods that would return instances of your class based on the same signature. Let's for example consider a Square class, we'll not worry about inheritance and just assume that we want four constructors to build our square:
  • one that takes in the length of a side
  • one that takes in the area
  • one that takes in the perimeter
  • one that takes in the diagonal
now all four of these constructors only require one parameter, so let's implement the approach we discussed before.

using System;

namespace pc.Tip
{
    class Square
    {
        public double Side { get; set; }

        public Square() { }

        public static Square InitSquareBySide(double Side)
        {
            return new Square { Side = Side };
        }
        public static Square InitSquareByArea(double Area)
        {
            return new Square { Side = Math.Sqrt(Area) };
        }

        public static Square InitSquareByPerimeter(double Perimeter)
        {
            return new Square { Side = Perimeter/4 };
        }

        public static Square InitSquareByDiagonal(double Diagonal)
        {
            return new Square { Side = Diagonal / Math.Sqrt(2) };
        }

    }
    class Program
    {
        static void Main(string[] args)
        {
            var s1 = Square.InitSquareByArea(9);
            Console.WriteLine(s1.Side);

            var s2 = Square.InitSquareBySide(5);
            Console.WriteLine(s2.Side);

            var s3 = Square.InitSquareByDiagonal(9);
            Console.WriteLine(s3.Side);

            var s4 = Square.InitSquareByPerimeter(20);
            Console.WriteLine(s4.Side);
        }
    }
}

There you have it, not exactly as advertised, but get's the job done, we could have also made the default constructor private forcing the user o use our Static instantiators(not a real word).