What’s New in C# 3.0

C# 3.0 features are centered on Language Integrated Query capabilities, or LINQ for short. LINQ enables SQL-like queries to be written directly within a C# program, and checked statically for correctness. Queries can execute either locally or remotely; the .NET Framework provides LINQ-enabled APIs across local collections, remote databases, and XML.

C# 3.0 features include:

  • Lambda expressions

  • Extension methods

  • Implicitly typed local variables

  • Query comprehensions

  • Anonymous types

  • Implicitly typed arrays

  • Object initializers

  • Automatic properties

  • Partial methods

  • Expression trees

Lambda expressions are like miniature functions created on the fly. They are a natural evolution of anonymous methods introduced in C# 2.0, and in fact, completely subsume the functionality of anonymous methods. For example:

	Func<int,int> sqr = x => x * x;
	Console.WriteLine (sqr(3));           // 9

The primary use case in C# is with LINQ queries, such as the following:

	string[] names = { "Tom", "Dick", "Harry" };

	// Include only names of >= 4 characters:

	IEnumerable<string> filteredNames =
	  Enumerable.Where (names, n => n.Length >= 4);

Extension methods extend an existing type with new methods, without altering the type’s definition. They act as syntactic sugar, making static methods feel like instance methods. Because LINQ’s query operators are implemented as extension methods, we can simplify our preceding query as follows:

	IEnumerable<string> filteredNames =
	  names.Where (n => n.Length >= 4);

Implicitly typed ...

Get C# 3.0 Pocket Reference, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.