c# avoid constructor redundancy

Sometimes we need to define several constructors that just get different types – but all do do same like the following here:

class MyClass
{
   int x;
   public int X { get => x; set => x = value; }

   MyClass(int x)
   {
      this.x = x;
      //... do further things
   }

   MyClass(string x)
   {
      this.x = int.Parse(x);
      //... do other further things
   }
}

But we can do this in a better way by inheriting from one constructor like this:

class MyClass
{
   int x;
   public int X { get => x; set => x = value; }

   MyClass(int x)
   {
      this.x = x;
      //... do further things
   }

   MyClass(string x) : this(int.Parse(x))
   {
      //... do other further things
   }
}

By doing this the string-parameter-constructor inherit the int-parameter-constructor and does every thing. We also could call the int-parameter-constructor -method in the string-parameter-parameter like “this(int.Parse(x))”.

Advertisements