Search code examples
c#objectinitializationinitialization-list

Base member initialization section C#?


Does a base member initialization section exist in C#? I tried searching and searching but kept coming up with questions regarding initializing the List class. The initialization list I am referring to looks like the example located here.

One reason for doing this is to initialize a constant in a class. I'm essentially trying to figure out if I can do the following:

public class A{
    private const string _name;
    public A(string name): _name(name){
         //stuff
    }
}

Again, I'm trying to do this in C#, not C++. Any thoughts?


Solution

  • No, C# does not support member initialization before constructor body the same way as C++ does. You can either initialize fields when they are declared or using normal assignament inside contructor body.

    The only 2 methods can be used at that position - call to contructor of base class and call to another contructor in the same class. You can check C# specification (i.e. http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-334.pdf, section 17.10 Instance constructors) for details:

    constructor-declaration:
        attributesopt constructor-modifiersopt constructor-declarator constructor-body
    
    constructor-declarator:
       identifier ( formal-parameter-listopt ) constructor-initializer
    constructor-initializer:
      : base ( argument-listopt )
      : this ( argument-listopt )