C# and arrays of anonymous objects

Yevhen picture Yevhen · Jan 9, 2010 · Viewed 62.5k times · Source

What does such an expression mean?

obj.DataSource = new[]
{
    new {Text = "Silverlight", Count = 10, Link="/Tags/Silverlight" },
    new {Text = "IIS 7", Count = 11, Link="http://iis.net" },
    new {Text = "IE 8", Count = 12, Link="/Tags/IE8" },
    new {Text = "C#", Count = 13, Link="/Tags/C#" },
    new {Text = "Azure", Count = 13, Link="?Tag=Azure" }
};

Especially these lines: new {Text = "IIS 7"... }

How can I create an array like this manually to suit this DataSource.

Answer

First, let's reformat that code a little:

obj.DataSource = new[]
{
    new {  Text = "Silverlight",  Count = 10,  Link = "/Tags/Silverlight"  },
    new {  Text = "IIS 7",        Count = 11,  Link = "http://iis.net"     }, 
    new {  Text = "IE 8",         Count = 12,  Link = "/Tags/IE8"          }, 
    new {  Text = "C#",           Count = 13,  Link = "/Tags/C#"           },
    new {  Text = "Azure",        Count = 13,  Link = "?Tag=Azure"         } 
};

This does not look like a multi-dimensional array, but rather like an array of 5 objects. These objects inside the array are of an anonymous type, created and initialized using new { ... }.

Concerning your question how you can manually create such an array to suit the data source: you seem to be doing exactly that with the above code.