Calling the constructor with default parameters instead of the default constructor

I want to call the constructor of the structure, which has default values ​​for all parameters. But when I call the dimensionless constructor MyRectangle, an undefined constructor is called. Why is this? Is it possible not to have a constructor not created from me?

using System;

namespace UebungClasses
{
    class Program
    {
        static void Main(string[] args)
        {
            MyRectangle sixRec = new MyRectangle(3, 2);
            MyRectangle oneRec = new MyRectangle();

            Console.WriteLine("area of six: " + sixRec.Area() + " area of one: " + oneRec.Area());
        }
    }

    public struct MyRectangle
    { 
        public MyRectangle(double w = 1, double l = 1)
        {
            width = w;
            length = l;
            Console.WriteLine("Width: " + width + " Lenght: " + length);
        }

        public double Area()
        {
            return width * length;
        }

        private double width;
        private double length;
    }
}
+4
source share
2 answers

No, basically. If you use new MyRectangle(), he will always prefer the default constructor (value: zero init in the case struct).

, xor - , , . , double .

- , , :

new MyRectangle(dummy: true)

dummy , , .

factory (static MyRectangle Create(...)) .

+3

, . generics, , .

, .

, , :

public struct MyRectangle
{
    private readonly bool isNotDefault;

    public MyRectangle(double w, double l)
    {
        isNotDefault = true;
        width = w;
        length = l;
    }

    public double Area()
    {
        //Notice the use of the properties,
        //not the backing fields.
        return Width * Length;             
    }

    private readonly double width, length;
    public double Width => isNotDefault ? width: 1;
    public double Length => isNotDefault ? length : 1;

    public override string ToString()
        => $"Width: {Width} Lenght: {Length}";
}

, , , , . , , : 0/0.

+1

Source: https://habr.com/ru/post/1692505/


All Articles