0

There is a code where that reads something from the XML and loads it into dictionary. Pls find the code below. I need to understand what new [] {header} does.

what is new [] doing here.Thanks in advance.

var headers = _doc.GetElementsByTagName("Header");
var header = headers[0];

_dict.Add("Header_" + headerId, new [] {header});
JJJ
  • 32,902
  • 20
  • 89
  • 102
Jayaraman
  • 147
  • 1
  • 11
  • 12
    http://msdn.microsoft.com/en-us/library/bb384090.aspx – Dennis Dec 22 '14 at 08:43
  • 1
    Relevant: [All possible C# array initialization syntaxes](http://stackoverflow.com/questions/5678216/all-possible-c-sharp-array-initialization-syntaxes) – p.s.w.g Dec 22 '14 at 08:44

5 Answers5

7

It's an implicitly typed array creation expression - it lets the compiler infer the array type, a bit like using var but for arrays. So in your case, it's equivalent to:

_dict.Add("Header_" + headerId, new XmlNode[] { header });

It was added in C# 3 along with var to support anonymous types. For example, you can write:

var people = new[]
{
    new { Name = "Jon", Home = "Reading" },
    new { Name = "Gareth", Home = "Cambridge" }    
};

You couldn't write that as explicitly typed array creation expression, because the type of the array elements doesn't have a name.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2

It adds a new Array with the contents of header.

Bongo
  • 2,933
  • 5
  • 36
  • 67
1

It is just for creating a new array. Since you use a collection initializer, The compiler knows the type from headers[0]

Flat Eric
  • 7,971
  • 9
  • 36
  • 45
1

You allocate a new array. The compiler decides of which type.

AxdorphCoder
  • 1,104
  • 2
  • 15
  • 26
1

new [] {header} is just creating a new instance of an array. The type of items the array is about to store is the type of the header object. There is no need to define for example: new string[] { "some string" }, a simple new[] { "some string" } is enough to create an array instance of type String.

Voltaic
  • 144
  • 2
  • 4