Upload
clint-edmonson
View
853
Download
0
Embed Size (px)
Citation preview
What's New in C# 3.0? What's New in C# 3.0?
Clint EdmonsonClint EdmonsonArchitect EvangelistArchitect EvangelistMicrosoft CorporationMicrosoft Corporationwww.notsotrivial.net www.notsotrivial.net
AgendaAgenda
C# Design ThemesC# Design Themes
New Features in ActionNew Features in Action
SummarySummary
For More Information…For More Information…
QuestionsQuestions
C# 3.0 - Design ThemesC# 3.0 - Design Themes
Improves on C# 2.0Improves on C# 2.0
100% Backwards Compatible100% Backwards Compatible
Language Integrated Query (LINQ)Language Integrated Query (LINQ)
New Features in ActionNew Features in Action
New Features in C# 3.0 New Features in C# 3.0
Local Variable Type InferenceLocal Variable Type Inference
Object InitializersObject Initializers
Collection InitializersCollection Initializers
Anonymous TypesAnonymous Types
Auto-Implemented PropertiesAuto-Implemented Properties
Extension MethodsExtension Methods
LambdasLambdas
Query ExpressionsQuery Expressions
LINQLINQ
Partial MethodsPartial Methods
Local Variable Type InferenceLocal Variable Type Inference
private static void LocalVariableTypeInference(){
// Using the new 'var' keyword you can declare variables without having // to explicity declare their type. At compile time, the compiler determines // the type based on the assignment.int x = 10;var y = x;
// Since the type inference happens at compile time, you cannot declare // a 'var' without an assignment//var a;
// Output the type name for yConsole.WriteLine( y.GetType().ToString() );
}
Object InitializersObject Initializers
private static void ObjectInitializers(){
// Simplest way to create an object and set it's propertiesvar employee1 = new Employee();employee1.ID = 1;employee1.FirstName = "Bill";employee1.LastName = "Gates";Console.WriteLine( employee1.ToString() );
// We can always add a parameterized constructor to simplify codingvar employee2 = new Employee( 2, "Steve", "Balmer" );Console.WriteLine( employee2.ToString() );
// New way to create object, providing all the property value assignments// Works with any publicly accessible properties and fieldsvar employee3 = new Employee() { ID=3, FirstName="Clint", LastName="Edmonson" };Console.WriteLine( employee3.ToString() );
}
Collection InitializersCollection Initializers
private static void CollectionInitializers(){
// Create a prepopulated listvar employeeList = new List<Employee> {
new Employee { ID=1, FirstName="Bill", LastName="Gates" },new Employee { ID=2, FirstName="Steve", LastName="Balmer" },new Employee { ID=3, FirstName="Clint", LastName="Edmonson" }
};
// Loop through and display contents of listforeach( var employee in employeeList ){
Console.WriteLine( employee.ToString() );}
}
Anonymous TypesAnonymous Types
private static void AnonymousTypes(){
var a = new { Name = "A", Price = 3 };Console.WriteLine( a.GetType().ToString() );Console.WriteLine( "Name = {0} : Price = {1}", a.Name, a.Price );
}
Auto-Implemented PropertiesAuto-Implemented Properties
public class Employee{
public int ID{
get;set;
}
public string FirstName{
get;set;
}
public string LastName{
get;set;
}}
Extension MethodsExtension Methodspublic static class StringExtensionMethods{
// NOTE: When using an extension method to extend a type whose source // code you cannot change, you run the risk that a change in the implementation// of the type will cause your extension method to break.//// If you do implement extension methods for a given type, remember the following // two points:// - An extension method will never be called if it has the same signature // as a method defined in the type.// - Extension methods are brought into scope at the namespace level. For example,// if you have multiple static classes that contain extension methods in a single // namespace named Extensions, they will all be brought into scope by the using // Extensions; namespace.//public static int WordCount( this String str ){
return str.Split( new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries ).Length;
}}
// Usagestring s = "Hello Extension Methods";int i = s.WordCount();
Partial MethodsPartial Methods
// Employee.cspublic partial class Employee{
public bool Terminated{
get { return this.terminated; }set{
this.terminated = value;this.OnTerminated();
}}private bool terminated;
}
// Employee.Customization.cspublic partial class Employee{
// If this method is not implemented// compiler will ignore calls to itpartial void OnTerminated(){
// Clear the employee's ID numberthis.ID = 0;
}}
LINQ ExpressionsLINQ Expressionsprivate static void LinqExpressions(){
// Create a list of employeesvar employeeList = new List<Employee> {
new Employee { ID=1, FirstName="Bill", LastName="Gates" },new Employee { ID=2, FirstName="Steve", LastName="Balmer" },new Employee { ID=3, FirstName="Clint", LastName="Edmonson" }
};
// Search the list for founders using a lambda expressionvar foudersByLambda = employeeList.FindAll(
employee => (employee.ID == 1 || employee.ID == 2) );Console.WriteLine( foudersByLambda.Count.ToString() );
// Display collection using a lambda expressionfoudersByLambda.ForEach( employee => Console.WriteLine( employee.ToString() ) );
}
Query Expressions & Expression TreesQuery Expressions & Expression Treesprivate static void QueriesAndExpressions(){
// Create a list of employeesvar employeeList = new List<Employee> {
new Employee { ID=1, FirstName="Bill", LastName="Gates" },new Employee { ID=2, FirstName="Steve", LastName="Balmer" },new Employee { ID=3, FirstName="Clint", LastName="Edmonson" }
};
// Retrieve the founders via a LINQ queryvar query1 = from employee in employeeList
where employee.ID == 1 || employee.ID == 2 select employee;
var founders = query1.ToList<Employee>();founders.ForEach( founder => Console.WriteLine( founder.ToString() ) );
// Retrieve the new hires via a LINQ query that returns an anonymous typevar query2 = from employee in employeeList
where employee.ID == 3 select new {
employee.FirstName,employee.LastName
};var newHires = query2.ToList();newHires.ForEach( newHire => Console.WriteLine( newHire.ToString() ) );
}
Best PracticesBest Practices
Features are listed in increasing complexityFeatures are listed in increasing complexity
Don’t use features because they are new or Don’t use features because they are new or coolcool
Leverage new features to improve code Leverage new features to improve code readability and maintainabilityreadability and maintainability
Decide as a team to start using new features Decide as a team to start using new features and use them consistentlyand use them consistently
For More Information…For More Information…
Visual C# Developer CenterVisual C# Developer Centerhttp://msdn2.microsoft.com/en-us/vcsharp/default.aspxhttp://msdn2.microsoft.com/en-us/vcsharp/default.aspx
Accelerated C# 2008Accelerated C# 2008 by Trey Nash (Apress 2007) by Trey Nash (Apress 2007)
Continue the conversation on my blog:Continue the conversation on my blog:www.notsotrivial.netwww.notsotrivial.net
Questions and AnswersQuestions and Answers
Submit text questions using the “Ask” button. Submit text questions using the “Ask” button.
Don’t forget to fill out the survey.Don’t forget to fill out the survey.
For upcoming and previously live webcasts: For upcoming and previously live webcasts: www.microsoft.com/webcast www.microsoft.com/webcast
Got webcast content ideas? Contact us at: Got webcast content ideas? Contact us at: http://go.microsoft.com/fwlink/?LinkId=41781http://go.microsoft.com/fwlink/?LinkId=41781