Prev | Current Page 421 | Next

Jon Skeet

"C# in Depth: What you need to master C# 2 and 3"

Stick with it??”
it will make sense in the long run, I promise.
Let??™s pretend we didn??™t have the Person class, and the only properties we cared
about were the name and age. Listing 8.4 shows how we could still build objects with
those properties, without ever declaring a type.
var tom = new { Name = "Tom", Age = 4 };
var holly = new { Name = "Holly", Age = 31 };
var jon = new { Name = "Jon", Age = 31 };
Console.WriteLine("{0} is {1} years old", jon.Name, jon.Age);
As you can tell from listing 8.4, the syntax for initializing an anonymous type is similar
to the object initializers we saw in section 8.3.2??”it??™s just that the name of the type is
missing between new and the opening brace. We??™re using implicitly typed local variables
because that??™s all we can use??”we don??™t have a type name to declare the variable
with. As you can see from the last line, the type has properties for the Name and Age,
both of which can be read and which will have the values specified in the anonymous
object initializer used to create the instance??”so in this case the output is ???Jon is 31 years
old.??? The properties have the same types as the expressions in the initializers??”string
for Name, and int for Age. Just as in normal object initializers, the expressions used in
anonymous object initializers can call methods or constructors, fetch properties, perform
calculations??”whatever you need to do.


Pages:
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433