1

I am trying to create a 2d array but I don't seem to be able to pass a value in the constructor.

For example

public class MyObj
{
    public string State {get; private set;}
    public MyObj(string s)
    {
         this.State = s;
    }
}

And in another class

private MyObj[,] Obj;
private void Setup()
{
    this.Obj = new MyObj[5,5];
}

When I review this.Obj the value of State is always null. I understand why but without looping over each item in the array (after it's created) and setting the State property (removing the private set) I'm not sure if I have other options?

Whilst I know the syntax is wrong, something like

this.Obj = new MyObj("default text for each item in array")[5,5,]
1
  • If MyObj has a default value, why not put it into the class itself? Something like public MyObj(string s) { State = string.IsNullOrEmpty(s) ? "default value" : s;}? Commented Nov 15, 2017 at 18:11

2 Answers 2

3

When you create an array of reference objects with new, each element is set to the default value of null. There is no syntax to pass the default element, so you need to fill the array manually using nested loops:

private void Setup() {
    this.Obj = new MyObj[5,5];
    int rows = codes.GetLength(0);
    int cols = codes.GetLength(1);
    for (var r = 0; r != rows ; r++) {
        for (var c = 0 ; c != cols ; c++) {
            Obj[r,c] = new MyObj("default text for each item in array");
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

When creating an array, you are only allocating space for the potential objects. You are not actually assigning any objects to those spaces. Defining the array as new MyObj[5,5] results in a 5x5 array consisting of all nulls. You would still need to initialize each member of the array. It's during this initialization that you can assign the default values.

Alternatively, you could use the inline initialization syntax.

var a = new MyObj[,]{ {new MyObj('default'), new MyObj('default2') ...}, {...} ...}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.