C# constructors overloading

C#ConstructorConstructor Overloading

C# Problem Overview


How I can use constructors in C# like this:

public Point2D(double x, double y)
{
    // ... Contracts ...

    X = x;
    Y = y;
}

public Point2D(Point2D point)
{
    if (point == null)
        ArgumentNullException("point");
    Contract.EndContractsBlock();

    this(point.X, point.Y);
}

I need it to not copy code from another constructor...

C# Solutions


Solution 1 - C#

public Point2D(Point2D point) : this(point.X, point.Y) { }

Solution 2 - C#

You can factor out your common logic to a private method, for example called Initialize that gets called from both constructors.

Due to the fact that you want to perform argument validation you cannot resort to constructor chaining.

Example:

public Point2D(double x, double y)
{
    // Contracts

    Initialize(x, y);
}

public Point2D(Point2D point)
{
    if (point == null)
        throw new ArgumentNullException("point");

    // Contracts

    Initialize(point.X, point.Y);
}

private void Initialize(double x, double y)
{
    X = x;
    Y = y;
}

Solution 3 - C#

Maybe your class isn't quite complete. Personally, I use a private init() function with all of my overloaded constructors.

class Point2D {

  double X, Y;

  public Point2D(double x, double y) {
    init(x, y);
  }

  public Point2D(Point2D point) {
    if (point == null)
      throw new ArgumentNullException("point");
    init(point.X, point.Y);
  }

  void init(double x, double y) {
    // ... Contracts ...
    X = x;
    Y = y;
  }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAleksandr VishnyakovView Question on Stackoverflow
Solution 1 - C#Mark CidadeView Answer on Stackoverflow
Solution 2 - C#João AngeloView Answer on Stackoverflow
Solution 3 - C#jp2codeView Answer on Stackoverflow