JNF
JNF

Reputation: 3730

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

I seem to remember some kind of short hand way to initialize fields of a class sent to a constructor, something like:

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

Any clues?

Upvotes: 2

Views: 2088

Answers (2)

JleruOHeP
JleruOHeP

Reputation: 10386

There is easy way to initialize class fields after constructor like this:

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

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

Upvotes: 4

Ed Swangren
Ed Swangren

Reputation: 124770

That would be C++, but you tagged your question C#. C# has no notion of initialization lists, you simply assign your fields in the constructor. You can however chain constructors or call a base class constructor in a similar manner

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

Upvotes: 2

Related Questions