master_ruko
master_ruko

Reputation: 879

Is there a way to initialize a private class member when using an object initializer?

I know this code doesn't work, because I tried it, but it gets the point across with what I want to accomplish. I'm using C# preview targeting Core 3.1

class MyClass
{
    public int size{ get; set; }
    private int[] myArray;

    public myClass()
    {
        myArray = new int[size];
    }

    public void SomeMethod()
    {
        var x = myArray[10]    <-- I want to be able to do this here
    }
}

public class MyOtherClass
{
    // I want this to still initialize myArray even though I didn't explicitly call a ctor
    var mc = new MyClass
    {
        size = 20;
    } 
}

When I run something like this, myArray get initialized to int[0]. I'm wondering if there is a syntax I'm unaware of that will make something like this work. The reason I'm asking is that I have like 10 variable that I need to use in a constructor call. That makes it a really long/ugly constructor signature and I don't like that. When I have more than 4 variables I like to use object initializers because it makes thinks less confusing for me.

Upvotes: 0

Views: 117

Answers (1)

HugoRune
HugoRune

Reputation: 13799

You can execute arbitrary code in a setter, so you could initialize myArray, whenever size is changed:

public int size { 
     get {return myArray.Length;} 
     set {myArray = new int[value];}
}
private int[] myArray = new int[0];

I am somewhat doubtful whether that makes the code more readable, but it should work

Upvotes: 3

Related Questions