Is there a way to initialize fields from a constructor in C #?

It seems that I remember some short way to initialize the fields of the class sent to the constructor, for example:

 Class A {
    int n;
    public A(int N) : n(N) {}
 }

Any clues?

+3
source share
2 answers

It will be C ++, but you noted your C # question. In C # there is no concept of initialization lists, you just assign your fields in the constructor. However, you can bind constructors or call the base class constructor in a similar way.

// call base class constructor before your own executes
public class B : A
{
    public B(int whatever)
        : base(something)
    {
        // more code here
    }
}

// call secondary constructor
public class B : A
{
    private int _something;

    public B() : this(10) { }

    public B(int whatever)
    {
        _something = whatever;
    }
}
+2

There is a simple way to initialize class fields after such a constructor:

public class A
  {
    public int N;
    public string S;
    public A() {}
  }

  class B
  {
     void foo()
     {
        A a = new A() { N = 1, S = "string" }
     }
  }
+3

All Articles