Graham Conzett
Graham Conzett

Reputation: 8454

Issues creating object literal using anonymous types in c#

I'm trying to build the c# approximation of a JavaScript object literal to be passed to a view model in asp.net MVC:

var obj = new dynamic[]{
    new { name: "Id", index: "Id", width: 40, align: "left" },
    new { name: "Votes", index: "Votes", width: 40, align: "left" },
    new { name: "Title", index: "Title", width: 200, align: "left"}
};

The compiler is throwing:

"An anonymous type cannot have multiple properties with the same name"

Stab in the dark I'm guessing it can't distinguish between the which property goes with which anonymous object, I've seen a similar error using LINQ.

Is there a better way to accomplish what I'm trying to do?

EDIT: This is in VisualStudio 2010 and .net Framework 4. Bala R's Answer seems to address the problem for previous versions though.

Upvotes: 3

Views: 1485

Answers (1)

Bala R
Bala R

Reputation: 109037

Can you try this?

var obj = new[]{
    new { name= "Id", index= "Id", width= 40, align= "left" },
    new { name= "Votes", index= "Votes", width= 40, align= "left" },
    new { name= "Title", index= "Title", width= 200, align= "left"}
};

and you should be able to access the anonymous class array like this

if (obj[0].align == "left")
{
   ...
}

Upvotes: 6

Related Questions