Good evening have class

class A { //куча полей public A(int a) { //куча кода } public A(double a) { this = new A(Math.Round(a)); // вот тут мне говорит, что так нельзя } } 

In the second constructor, you need to implement absolutely the same thing as the first, but with a rounded value. There may be a large number of fields, so I don’t want to do this using a separate method.

How to make the second constructor work? I know that it is possible through inheritance, but how to manage without it in this situation?

    2 answers 2

    Try through this syntax

     public A(double a): this((int)a){} 

    To call another constructor from a constructor through new fraught with memory leaks, since in fact, 2 objects will be created.

    • Well, there won't be memory leaks, it's a language with a garbage collector. But this assign does not work, it is read-only. - VladD
    • @VladD in s worked, but never tried it here) - pavel
    • @VladD what is meant by the phrase read-only? The compiler said the same thing, but I’m not catching up with something) - koshachok
    • @koshachok: It means, it is intended only for reading, not for writing. - VladD
      public static A GetAObject(double a) { return new A((int)Math.Round(a)); } class Program { static void Main(string[] args) { //а так создаём объект, тут нет слова new var aObj = A.GetAObject(22.222); } }