views:

66

answers:

2

When i declare

object o = new { name = "Bruce",Age=21 };
Console.WriteLine("name={0},age={1}",???,??? );

Now how can i print value of name and age?

+6  A: 

Dont assign to an object variable, use var:

var o = new { name = "Bruce", Age = 21 };
Console.WriteLine( "name={0},age={1}, o.name, o.Age );
LBushkin
This is only possible in C# 3.0 upwards...
James
@James: Anonymous types in C# only exist beginning in v 3.0 of the language. So to use them you need implicitly typed variables, which is one of the reasons var was introduced.
LBushkin
ofcourse I am using C# 3.0 only,so it would be helpful,Thanks to Bushkin.
+3  A: 

While not accessing the properties directly (see LBushkin's answer). ToString() is overloaded to list the content of all of the properties

var o = new { name = "Bruce", Age = 21 };
Console.WriteLine(o);// { name = Bruce, Age = 21 }
Matthew Whited