Monday, October 12, 2009

C#3.0 Session at TechEd2007 - Code Samples

Thursday, June 07, 2007 1:42 PM

I just presented my C#3.0 session at TechEd Orlando titled "DEV346 - Microsoft Visual C# Under the Covers: An In-Depth Look at C# 3.0". The talk introduces the new C# language features and takes a tour behind the scenes of LINQ to Objects to see how C# is used to enable creating rich new kinds of APIs.


Here are the code samples from the talk:


File iconFirstDemo.cs File iconSecondDemo.cs


And here's a little in-line snippet - the results of the first demo:


using System;
using System.Collections.Generic;
using System.Linq;

class Customer
{
// C#3.0 Feature: Auto-Implemented Properties
public string CustomerID { get; set; }
public string ContactName { get; set; }
public string City { get; set; }
}

class Program
{
static void Main(string[] args)
{
List customers = LoadCustomers();

// C#3.0 Feature: Query Expressions
var query = from c in customers
where c.City == "London"
orderby c.ContactName.Split(' ')[1]
select new { c.CustomerID, c.ContactName };

foreach (var item in query)
Console.WriteLine("{0}, {1}", item.CustomerID, item.ContactName);
}

private static List LoadCustomers()
{
// C#3.0 Feature: 'var' - Local Variable Type Inference
// C#3.0 Feature: Collection Initializers
var customers = new List()
{
// C#3.0 Feature: Object Initializers
new Customer { CustomerID = "ALFKI",
ContactName = "Maria Anders",
City = "Berlin"},
new Customer { CustomerID = "ANATR",
ContactName = "Ana Trujillo",
City = "M?xico D.F."},
// more customers ...
new Customer { CustomerID = "WOLZA",
ContactName = "Zbyszek Piestrzeniewicz",
City = "Warszawa"}
};

return customers;
}
}

No comments:

Post a Comment