Code Listings
Chapter 1: Introducing C# and the .NET Framework
Quick Preview: What's new in C# 3.0:
Lambda expressions:
Func<int,int> square = x => x * x; Console.WriteLine (square(3)); // 9
LINQ queries:
string[] names = { "Tom", "Dick", "Harry" };
IEnumerable<string> filteredNames = // Include only names
Enumerable.Where (names, n => n.Length >= 4); // of >= 4 characters.
Extension methods:
string[] names = { "Tom", "Dick", "Harry" };
IEnumerable<string> filteredNames = names.Where (n => n.Length >= 4);
Implicitly typed local variables:
var filteredNames = names.Where (n => n.Length == 4);
Query comprehension syntax:
var filteredNames = from n in names where n.Length >= 4 select n;
Anonymous types:
var query = from n in names where n.Length >= 4
select new {
Name = n,
Length = n.Length
};
var dude = new { Name = "Bob", Age = 20 };
Implicitly typed arrays:
var dudes = new[]
{
new { Name = "Bob", Age = 20 },
new { Name = "Rob", Age = 30 }
};
Object initializers:
// C# 3.0
Bunny b1 = new Bunny { Name="Bo", LikesCarrots=true, LikesHumans=false };
// C# 2.0
Bunny b2 = new Bunny();
b2.Name = "Bo";
b2.LikesHumans = false;
Automatic properties:
public class Stock
{
// C# 3.0:
public decimal X { get; set; }
// C# 2.0:
private decimal y;
public decimal Y
{
get { return y; }
set { y = value; }
}
}
Partial methods:
// PaymentFormGen.cs — auto-generated
partial class PaymentForm
{
...
partial void ValidatePayment (decimal amount);
}
// PaymentForm.cs — hand-authored
partial class PaymentForm
{
...
partial void ValidatePayment (decimal amount)
{
if (amount > 100)
...
}
}
Expression trees:
Expression<Func<string,bool>> predicate = s => s.Length > 10;
© 2007, O'Reilly Media, Inc. All rights reserved