Can we have the body for the default constructor in C # at run time?

There will be a constructor in the class. If the programmer determines that then definitely he will have a body. But if we do not define it, will this constructor have a default body in it?

+3
source share
6 answers

If you leave the default constructor implementation to the compiler (what happens if you do not define it), the constructor will initialize all the default fields For example.

class With<T>
{
  T field;
  string str;
  With()
  {
    field = default(T);
    str = "";
  }
}

class WithOut<T>
{
  T field;
  string str = "";
}

from the functional point of view will have the same default constructor

0
source

If you have the following class:

class A { }

, . , :

class A 
{ 
    private string someField = "some text";
}

... .

+3

, , . , / .

0

, , .

0

- , , , , ( default ). , , . , , ; .

0

, , object. ...

public object()
{
}

, :

public sealed class Person
{
    public string Name = string.Empty;
    public string Firstname = string.Empty;
    public string Middlename = string.Empty;

    public string Fullname
    {
        get { return string.Concat(Name, Firstname, Middlename); }
    }

}

:

public Person()
{
    this.Name = string.Empty;
    this.Firstname = string.Empty;
    this.Middlename = string.Empty;
}

EDIT: if you use the .NET Reflector, you can parse the assemblies to see what is really happening.

0
source

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