Home > Net >  Array of objects
Array of objects

Time:12-26

Border[] _headerBorder = new Border[] {
    new Border{}, new Border{}, new Border{}, new Border{}, new Border{},
    new Border{}, new Border{}, new Border{}, new Border{}, new Border{},
    new Border{}, new Border{}, new Border{}, new Border{}, new Border{},
    new Border{}, new Border{}, new Border{}, new Border{}, new Border{}
};

How can I shorten this type of declaration?

CodePudding user response:

Shorten means what?

I would better go with the below If I need to create an array with 20 elements.

Border[] _headerBorder = new Border[20];

for (int i = 0; i < _headerBorder.Length; i  )
{
    _headerBorder[i] = new Border();
}

Edit: As per the comment by @Rand random, you could also do it like this.

for (int i = 0; i < _headerBorder.Length; i  )
    _headerBorder[i] = new ();

CodePudding user response:

This is basically a for loop flattened into a single line of code:

var _headerBorder = Enumerable.Range(1, 20).Select(i => new Border()).ToArray();
  • Related