Книга: C# 2008 Programmer
Anonymous Types (C# 3.0)
Anonymous Types (C# 3.0)
C# 3.0 introduces a new feature known as anonymous types. Anonymous types enable you to define data types without having to formally define a class. Consider the following example:
var book1 = new {
ISBN = "978-0-470-17661-0",
Title="Professional Windows Vista Gadgets Programming",
Author = "Wei-Meng Lee",
Publisher="Wrox"
};
Chapter 3 discusses the new C# 3.0 keyword var
.
Here, book1 is an object with 4 properties: ISBN
, Title
, Author
, and Publisher
(see Figure 4-1).
Figure 4-1
In this example, there's no need for you to define a class containing the four properties. Instead, the object is created and its properties initialized with their respective values.
C# anonymous types are immutable, which means all the properties are read-only — their values cannot be changed once they are initialized.
You can use variable names when assigning values to properties in an anonymous type; for example:
var Title = "Professional Windows Vista Gadgets Programming";
var Author = "Wei-Meng Lee";
var Publisher = "Wrox";
var book1 = new {
ISBN = "978-0-470-17661-0",
Title,
Author,
Publisher
};
In this case, the names of the properties will assume the names of the variables, as shown in Figure 4-2.
Figure 4-2
However, you cannot create anonymous types with literals, as the following example demonstrates:
//---error---
var book1 = new {
"978-0-470-17661-0",
"Professional Windows Vista Gadgets Programming",
"Wei-Meng Lee",
"Wrox"
};
When assigning a literal value to a property in an anonymous type, you must use an identifier, like this:
var book1 = new {
ISBN = "978-0-470-17661-0",
Title="Professional Windows Vista Gadgets Programming",
Author = "Wei-Meng Lee",
Publisher="Wrox"
};
So, how are anonymous types useful for your application? Well, they enable you to shape your data from one type to another. You will look into more about this in Chapter 14, which tackles LINQ.