开发者

Can we have a body for a default constructor in C# during runtime?

In a class there will be a constructor.If a programmer defines that then definitely it will have a body. But if we don't defi开发者_JAVA技巧ne it then will that constructor will have a default body in it?


If you have the following class:

class A { }

There will be an empty constructor created by the compiler. If you add some field with initializations, like so:

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

...the generated constructor body will contain the code to assign the value to the field.


If you leave the implementation of the default constructor to the compiler (which is what happens if you don't define it) then the constructor will initialize all fields to their default values E.g.

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

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

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


If you don't define a constructor, there will be a default empty constructor that will be considered internally by the compiler. It can be used to create new instances for that class, not to assign class properties/ members.


The default constructor will not do anything, it is just there to fulfil the requirement that a class has a constructor.


If you do not define any constructors, a default one is created for you, but it doesn't do anything other than set your properties to their default values (as specified in your class definition, or by using the default operator). If you define a parameterless constructor, then it has whatever body you specify. If you define any constructors that take parameters, then you must manually define a parameterless constructor; the compiler will not create one for you in this case.


Each class that you define inherits from object. The default constructor body would be like this...

public object()
{
}

So if you have a class like this:

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); }
    }

}

Then the constructor will look like this...

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

EDIT: If you use .NET Reflector you can disassemble the assemblies to have a look at what is really going on.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜