Enriquev
Enriquev

Reputation: 929

Setting attributes on anonymous objects

I thought this was possible in c# .net 2.0 ?

header.Cells.Add((new TableCell(){Text = "First header"}));

unless I am doing it wrong? this produces the following error:

CS1026: ) expected

Were is the mistake?

Upvotes: 1

Views: 137

Answers (5)

Justin
Justin

Reputation: 86729

The support for this syntax is provided by the compiler, not the .Net runtime / CLR.

If you are using Visual Studio 2008 or later you can use this syntax perfectly fine while targeting .Net 2.0, if not then you will need to do this the "normal" way.

Also you have an additional pair of redundant parentheses - you may find it easier to use the following layout when using this syntax:

header.Cells.Add(new TableCell() 
{
    Text = "First header" 
});

Upvotes: 0

Brandon Moretz
Brandon Moretz

Reputation: 7621

That's not an anonymous object, TableCell is a predefined type. You're referring to implicit object initialization syntax which was introduced in C# 3.0, you'll have to do it the "old fashioned" way.

Upvotes: 0

Adam Robinson
Adam Robinson

Reputation: 185643

Property initializer syntax was introduced in C# 3.0; it is not valid syntax in C# 2.0.

Upvotes: 2

Schroedingers Cat
Schroedingers Cat

Reputation: 3129

I don't think you can set the properties in the declaration in 2.0. So you will have to do:

TableCell tc=new TableCell();
tc.Text = "First header";
header.Cells.Add(tc);

Upvotes: 0

pblasucci
pblasucci

Reputation: 1778

I'm not sure about C# 2.0... but in C# 3.0 you can do this instead:

header.Cells.Add((new TableCell{ Text = "First header" }));

Upvotes: 0

Related Questions