Search code examples
c#.netclass-design

static construction method vs constructor


In the .NET framework I often see the idiom where a constructor is replaced by a static function to construct a new object from.

For instance with BigInteger there's no constructor taking a string so this is not possible:

BigInteger i = new BigInteger("1000000103453543897");

But there is a static Parse function.

BigInteger i = BigInteger.Parse("1000000103453543897");

Why is a class design like this often chosen?

The only thing I can think of is there's one object less to be created and later thrown away. Is it true that that is the main reason? Or are there other reasons?

BigInteger(string value)
{
  BigInteger result = new BigInteger(); // this one just returned in a Parse function

  // compute bigint

  // copy result to this
  data = new uint[maxLength];
  for (int i = 0; i < result.Length; i++)
    data[i] = result.data[i];

  Length = result.dataLength;  
}

Solution

  • There could be many reasons - research the Factory method pattern.

    With your example - many consider it a bad practice to have significant logic in/called from a constructor (I don't want to throw an exception from a constructor unless it's a missing parameter). Using a factory method allows for implementation guaranteed to run at object construction but not in the constructor.