Module 2: C# 3.0 Language Enhancements (Material)

29
Visual Studio 2008 Community Training By Mohamed Saleh [email protected] www.jordev.net www.geeksconnected.com/mohamed

description

Module 2: C# 3.0 Language Enhancements (Material)Jordan .NET User Group (Jordev)Community MaterialMohamed Saleh

Transcript of Module 2: C# 3.0 Language Enhancements (Material)

Page 1: Module 2: C# 3.0 Language Enhancements (Material)

Visual Studio 2008 Community Training

By

Mohamed Saleh

[email protected]

www.jordev.net

www.geeksconnected.com/mohamed

Page 2: Module 2: C# 3.0 Language Enhancements (Material)

MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS

2

MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS

Table of Contents

Official Community Material License 3

Module Overview 4

Automatically Implemented Properties 5

Lab 1: Using Auto-Implemented Properties 6

Object and Collection Initializers 8

Lab 2: Using Initializers 10

Implicit Typing 14

Lab 3: Using Implicit Typing 16

Extension Methods 19

Lab 4: Using Extension Methods 21

Lambda Expressions 24

Lab 5: Writing Expression Methods 25

Summary 28

References 29

Page 3: Module 2: C# 3.0 Language Enhancements (Material)

MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS

3

Official Community Material License

While every precaution has been taken in the preparation of this document, Jordev assumes no responsibility for

errors, omissions, or for damages resulting from the use of the information herein.

This disclaimer statement, presented on this page, is an integral part of this document. Should this page of the

document, in its electronic or printed formats, be lost, deleted, destroyed or otherwise discarded, this disclaimer

statement applies despite the consequences.

© 2008 Jordev.NET. All rights reserved.

The names of actual companies and products mentioned herein may be the trademarks of their respective owners.

Page 4: Module 2: C# 3.0 Language Enhancements (Material)

MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS

4

Module Overview

This module introduces you to the new enhancements over the C# language version 3.0. C#

3.0 contains several key language enhancements build on C# 2.0 to increase the developers

productivity, these new enhancements provide the core for the LINQ Project.

Objectives:

After completing this module, you will be able to:

Automate the process of creating properties with trivial implementation.

Enhance the objects and collections using the Initializers.

Create implicitly typed local variables.

Extend existing types using Extension Methods.

Write the new lambda expressions.

Page 5: Module 2: C# 3.0 Language Enhancements (Material)

MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS

5

Automatically Implemented Properties

The Auto Implemented Properties feature can handle the properties with trivial

implementation (The unused getter and setter) by delegating the task of generating private

fields to the compiler; the compiler will generate hidden backing fields with the

implementation, the compiler use a specific syntax which make the fields inaccessible to

developers by using special identifiers which is not allowed with the C# identifiers in order to

not to conflict with any other fields written by the developer.

The following code illustrates the creation of properties using C# 2.0 and C# 3.0:

//C# 2.0 Version

public class Student

{

private string _name;

public string Name

{

get { return _name; }

set { _name = value; }

}

}

======================================================================================

//C# 3.0 Version

public class Student

{

public string Name { get; set; }

}

This feature is related to the compiler and not the Framework Version or the Intermediate

Language, which mean it can be used with .NET Framework 2.0 and 3.0.

Page 6: Module 2: C# 3.0 Language Enhancements (Material)

MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS

6

Lab 1: Using Auto-Implemented Properties

After completing this lab, you will be able to:

Use the Automatic Implemented Properties.

Creating read-only and write-only properties.

Using Automatic Implemented Properties with multi-framework versions.

Examining the effects of the Automatic Implemented Properties on the generated

intermediate language.

Using the Auto Implemented Properties

1. On the File menu in Visual Studio 2008, point to New and then click Project.

2. In the New Project dialog box, select a language, and then select Windows in the

Project Types box.

3. In the Templates box, select Console Application.

4. In the Location box, type the path to where to create the application, and then click

OK.

5. In the Visual Studio code editor as the following code:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace GeeksConnected.Module02Lab01

{

Page 7: Module 2: C# 3.0 Language Enhancements (Material)

MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS

7

internal class Student

{

public long ID { get; private set; }

public string Name { get; set; }

public string Course { get; set; }

public string Level { private get; set; }

public Student(long id)

{

this.ID = 10;

}

}

public class AutoPropertiesLab

{

static void Main()

{

Student st1 = new Student(20);

st1.Name = "Omar";

st1.Level = "A";

st1.Course = "Introduction To C# 3.0";

Console.WriteLine("Student Information");

Console.WriteLine("===================");

Console.WriteLine("Student Name : {0}",st1.Name);

Console.WriteLine("Student ID : {0}",st1.ID.ToString());

Console.WriteLine("Student Course: {0}",st1.Course);

Console.WriteLine("Press any key to exit...");

Console.ReadKey();

}

}

}

6. Click Start on the Debug menu or press F5 to run the code.

Using Automatic Implemented Properties with Different Framework Versions

7. Right-click the project in the Solution Explorer and then click Properties.

8. On the Application tab, Go to the Target Framework drop-down list; click a .NET

Framework Version 2.0.

9. Run the code by pressing F5, the application will works properly with different

Framework Versions.

Examining the Generated Hidden Backing Field

1. Open Visual Studio 2008 Command Prompt from the Start -> Programs ->

Microsoft Visual Studio 2008 -> Visual Studio Tools.

2. On the Command Prompt change the directory to C:\Labs\Module02Lab01\bin\Debug\

and then type ILdasm Module02Lab01.exe, the IL Disassembler will show the

generated backing fields under the class GeeksConnected.Module02Lab01.Student.

Page 8: Module 2: C# 3.0 Language Enhancements (Material)

MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS

8

Object and Collection Initializers

Object Initializers Overview:

The standard way to initialize object is by passing the initial values to a parameterize

constructor, which requires some little code to build the parameterized constructor, or by

assigning the values to the properties directly.

C# 3.0 supports the concept of “Object Initializers” which allows the developer to create the

object instance and assign the initial values at the same time.

Defining Object Initializers:

“An object initializer consists of a sequence of member Initializers, enclosed by { and } tokens

and separated by commas. Each member initializer must name an accessible field or property

of the object being initialized, followed by an equals sign and an expression or an object

initializer or collection initializer.” Ref 5

The following example defines a new class “customer”, and then initialize in different ways:

1. Using the parameterized constructor:

//C# Version 2.0

Customer cst1 = new Customer(1,"Osama Asad","077-098-098-7");

2. Assigning the properties values directly:

//C# Version 2.0

Customer cst2 = new Customer();

cst2.ID = 2;

cst2.Name = "Ayman Farouk";

cst2.Phone = "0799-987-980-98";

3. Using the Object Initializer:

//C# Version 3.0: Using Object Initializer:

Customer cst3 = new Customer() { ID = 3, Name = "Osama Salam", Phone = "074-545-

545-67" };

Page 9: Module 2: C# 3.0 Language Enhancements (Material)

MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS

9

Collection Initializers Overview:

The collection Initializers allows the developer to specify one or more elements Initializers

when initializing any type that implements the System.Collections.Generic.IEnumerable<T>.

Defining Collection Initializer:

“A collection initializer consists of a sequence of element initializers, enclosed by { and }

tokens and separated by commas. Each element initializer specifies an element to be added to

the collection object being initialized, and consists of a list of expressions enclosed by { and }

tokens and separated by commas. ” Ref 5

The following examples illustrate the classic way to initialize collections and the new way:

1. The classic way of initializing collections:

//C# Version 2.0

Customer cst1 = new Customer();

cst1.ID = 2;

cst1.Name = "Ayman Farouk";

cst1.Phone = "0799-987-980-98";

Customer cst2 = new Customer(3, "Osama Salam", "074-545-5");

List<Customer> CSTs = new List<Customer>();

CSTs.Add(cst1);

CSTs.Add(cst2);

2. Initializing Collections using the Collection Initializers:

List<Customer> CSTs = new List<Customer>()

{

new Customer() {ID = 1,Name = "Osama", Phone="07654332"},

new Customer() {ID = 2, Name = "Omar", Phone="06543267"},

new Customer() {ID= 3, Name = "Ahmad", Phone = "0744444"}

};

Initializers Rules:

1. Object Initializers cannot include more than one member initializer for the same field or

property.

2. The Object Initializers cannot refer to the newly created object it is initializing.

3. The Collection type must implements System.Collections.Generic.IEnumerable<T> in order

to have initializers.

Page 10: Module 2: C# 3.0 Language Enhancements (Material)

MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS

10

Lab 2: Using Initializers

After completing this lab, you will be able to:

Writing Object Initializer expressions.

Writing Collection Initializer expressions.

Using the nested object initializer.

Using Initializers with multi-framework versions.

Examining the generated initialization instructions in the intermediate language.

Using the Initializers

1. On the File menu in Visual Studio 2008, point to New and then click Project.

2. In the New Project dialog box, select a language, and then select Windows in the

Project Types box.

3. In the Templates box, select Console Application.

4. In the Location box, type the path to where to create the application, and then click

OK.

5. In the Visual Studio code editor as the following code:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace GeeksConnected.Module02Lab02

{

Page 11: Module 2: C# 3.0 Language Enhancements (Material)

MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS

11

class Customer

{

public long ID { get; set; }

public string Name { get; set; }

public string Company { get; set; }

public Phone phone { get; set; }

public Customer ReferalCustomer { get; set; }

public Customer()

{

}

}

class Phone

{

public int CountryCode;

public int AreaCode;

public int phone;

public Phone()

{

}

public override string ToString()

{

return CountryCode.ToString() + AreaCode.ToString() + phone.ToString();

}

}

class Module02Lab02

{

static void Main()

{

string refCustomer1, refCustomer2, refCustomer3;

List<Customer> custList = new List<Customer>

{

new Customer

{

Name = "Samer", ID = 1, Company = "Microsoft"

},

new Customer

{

Name = "Muhanad", ID = 2, Company = "Great Package",

phone = new Phone { CountryCode = 962, AreaCode = 6,

phone = 111111 }

},

new Customer

{

Name = "Mohamed", ID = 3, Company = "Estarta",

phone = new Phone { CountryCode = 962, AreaCode = 5,

phone = 1234567},

ReferalCustomer = new Customer {Name = "Muhanad", ID = 2,

Company = "Great Package"}

},

new Customer

{

Name = "Ayman", ID = 4, Company = "Microsoft",

phone = new Phone{ CountryCode = 966, AreaCode = 8,

phone = 876544332},

ReferalCustomer = new Customer

{

Page 12: Module 2: C# 3.0 Language Enhancements (Material)

MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS

12

Name = "Mohamed", ID = 3, Company = "Estarta",

phone = new Phone { CountryCode = 962, AreaCode = 5,

phone = 1234567},

ReferalCustomer = new Customer

{

Name = "Muhanad", ID = 2,

Company = "Great Package",

ReferalCustomer = new Customer

{

Name = "Samer", ID = 1, Company = "Microsoft"

}

}

}

}

};

foreach (Customer cus in custList)

{

Console.WriteLine("Customer Information:");

Console.WriteLine("=====================");

Console.WriteLine("Customer ID : {0}", cus.ID);

Console.WriteLine("Customer Name : {0}", cus.Name);

Console.WriteLine("Customer Company: {0}", cus.Company);

if (cus.phone != null)

{

Console.WriteLine("Customer Phone : {0}",

cus.phone.ToString());

}

if (cus.ReferalCustomer != null)

{

Console.WriteLine("Customer Referal: {0}",

cus.ReferalCustomer.Name);

if (cus.ReferalCustomer.ReferalCustomer != null)

{

refCustomer1 = cus.ReferalCustomer.Name;

refCustomer2 = cus.ReferalCustomer.ReferalCustomer.Name;

Console.WriteLine("{0} referal is {1}", refCustomer1,

refCustomer2);

if (cus.ReferalCustomer.ReferalCustomer.ReferalCustomer != null)

{

refCustomer1 = cus.ReferalCustomer.Name;

refCustomer2 = cus.ReferalCustomer.ReferalCustomer.Name;

refCustomer3 =

cus.ReferalCustomer.ReferalCustomer.ReferalCustomer.Name;

Console.WriteLine("{0} refer to {1} whose refer to {2}",

refCustomer1, refCustomer2, refCustomer3);

}

}

}

Console.WriteLine("Press Any Key To continue...");

Console.ReadKey();

}

}

}

}

6. Click Start on the Debug menu or press F5 to run the code.

Using the Initializers with Different Framework Versions

Page 13: Module 2: C# 3.0 Language Enhancements (Material)

MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS

13

7. Right-click the project in the Solution Explorer and then click Properties.

8. On the Application tab, Go to the Target Framework drop-down list; click a .NET

Framework Version 2.0.

9. Run the code by pressing F5, the application will works properly with different

Framework Versions.

Examining the Generated initialization instructions Field

10. Open Visual Studio 2008 Command Prompt from the Start -> Programs ->

Microsoft Visual Studio 2008 -> Visual Studio Tools.

11. On the Command Prompt change the directory to C:\Labs\Module02Lab02\bin\Debug\

and then type ILdasm Module02Lab02.exe, the IL Disassembler will show the

generated initialization instructions under the class Student.

Page 14: Module 2: C# 3.0 Language Enhancements (Material)

MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS

14

Implicit Typing

Implicit Typing Overview:

The new C# compiler can infers the type of variables by using the new keyword var to

declare the variables. When using the var keyword the compiler will check the right side of

the initialization statement, and it will determines and assigns the most appropriate type.

The var keyword doesn’t act like the Variant in Visual Basic 6.0 and COM programming,

declaring instances using Variant results in loosely typed object, but var gives you a strong

typed object.

Implicit Typing Contexts:

The var keyword can be used in the following contexts:

1. Declaring variable at the method/property scope

static void Main(string[] args)

{

var i = 10;

var strName = "GeeksConnected";

}

2. In a for loop statement.

for (var intCounter = 0; intCounter < length; intCounter++) {…}

3. In a foreach loop statement.

foreach (var item in collection) {…}

4. In a using statement.

using (var sr = new StreamWriter("...")){…}

Page 15: Module 2: C# 3.0 Language Enhancements (Material)

MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS

15

Implicit Typing Rules:

1. When declaring any variable using var, the value of variable must be initialized.

var intNum;//illegal...

var intNum = 10; ;//allowed

2. It’s illegal to declare variables using var at the class scope or using it as field.

class Module02Lab03

{

var intNum;//illegal...

3. var is not considered as a keyword, so its allowed to use it as an instance name, but in

this case it’s not allowed to use var in the same scope.

static void Main(string[] args)

{

string var;

var i = 10;

4. It’s illegal to use variables declared using var in initialization expressions.

var intNumber = intNumber + 10;

5. Implicit typed variables cannot be used as return value or parameters.

public var GetCustomerInformation(var CustomerNum) {…}

Page 16: Module 2: C# 3.0 Language Enhancements (Material)

MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS

16

Lab 3: Using Implicit Typing

After completing this lab, you will be able to:

Using implicit-typed variables.

Using implicit typing with foreach context.

Using implicit typing with custom classes and lists.

Using Implicit Typing with multi-framework versions.

Examining the types of the implicit-typed variables.

Using the Implicit Typing

1. On the File menu in Visual Studio 2008, point to New and then click Project.

2. In the New Project dialog box, select a language, and then select Windows in the

Project Types box.

3. In the Templates box, select Console Application.

4. In the Location box, type the path to where to create the application, and then click

OK.

5. In the Visual Studio code editor as the following code:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace GeeksConnected.Module02Lab03

{

Page 17: Module 2: C# 3.0 Language Enhancements (Material)

MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS

17

class Module02Lab03

{

class Student

{

public long RegID { get; set; }

public string Name { get; set; }

public string Company { get; set; }

public Student()

{

}

}

static void Main(string[] args)

{

var st1RegID = 10;

var st1Name = "Hikmet";

var st1Company = "ABC";

var st1 = new Student();

st1.RegID = st1RegID;

st1.Name = st1Name;

st1.Company = st1Company;

var Students = new List<Student>

{

new Student { RegID = 1, Company = "XYZ", Name = "Muhannad"},

new Student { RegID = 1, Company = "ABC", Name = "Mohamed"},

new Student { RegID = 1, Company = "GP", Name = "Osama"},

new Student { RegID = 1, Company = "MS", Name = "Ahmed"},

new Student { RegID = 1, Company = "East", Name = "Omar"},

};

Students.Add(st1);

Console.WriteLine("Types Information");

Console.WriteLine("=================");

Console.WriteLine(st1RegID.GetType().ToString());

Console.WriteLine(st1Name.GetType().ToString());

Console.WriteLine(st1Company.GetType().ToString());

Console.WriteLine(st1.GetType().ToString());

Console.WriteLine(Students.GetType().ToString());

Console.WriteLine("Press Any Key To Continue..");

Console.ReadKey();

Console.WriteLine("Students Information");

Console.WriteLine("=================");

foreach (var item in Students)

{

Console.WriteLine("Name : {0}",item.Name);

Console.WriteLine("ID : {0}",item.RegID);

Console.WriteLine("Company: {0}", item.Company);

Console.WriteLine("\n");

}

Console.WriteLine("Press Any Key To Exit...");

Console.ReadKey();

}

}

}

Page 18: Module 2: C# 3.0 Language Enhancements (Material)

MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS

18

6. Click Start on the Debug menu or press F5 to run the code.

Using the Initializers with Different Framework Versions

7. Right-click the project in the Solution Explorer and then click Properties.

8. On the Application tab, Go to the Target Framework drop-down list; click a .NET

Framework Version 2.0.

9. Run the code by pressing F5, the application will works properly with different

Framework Versions.

Page 19: Module 2: C# 3.0 Language Enhancements (Material)

MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS

19

Extension Methods

Extension Methods Overview:

Extension Methods feature allows the developer to inject new methods and functionalities to

the existing compiled types (classes, interfaces implementation, structures), without the need

to re-write or override the current implementations.

One of the most useful examples that show the powerful of extension methods is the LINQ

operators that add different query functionalities to the existing System.Collections.IEnumerable,

and System.Collections.Generic.IEnumerable(T) types, such as OrdeyBy and Average operators.

Extension Methods are natively supported in the Visual Studio 2008 development

environment which provides an intellisense support in the code editor.

Defining Extension Methods:

The following guidelines illustrate how to define extension methods:

1. The extension methods must be defined in separated static class.

2. The extension methods must be declared as static methods.

3. The first parameter modifier of the extension methods must be this keyword.

The following example illustrates how to declare extension method:

public static class Extensions

{

public static void print (this string s)

{

Console.WriteLine(s);

}

}

Page 20: Module 2: C# 3.0 Language Enhancements (Material)

MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS

20

Extension Methods Limitations:

The following limitations must be considered while implementing the extension methods:

1. The extension methods cannot be declared in generic or nested static classes.

2. The extension methods cannot be used to create properties, operators, or events.

3. Types can be extended only in .NET Framework 3.5

Page 21: Module 2: C# 3.0 Language Enhancements (Material)

MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS

21

Lab 4: Using Extension Methods

After completing this lab, you will be able to:

Extending types with extension methods.

Consuming extension methods.

Extending different .NET Framework built-in types.

Implementing and using extension methods

10. On the File menu in Visual Studio 2008, point to New and then click Project.

11. In the New Project dialog box, select a language, and then select Windows in the

Project Types box.

12. In the Templates box, select Console Application.

13. In the Location box, type the path to where to create the application, and then click

OK.

14. In the Visual Studio code editor as the following code:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace GeeksConnected.Module02Lab04

{

public class Student

{

public long RegID { get; set; }

Page 22: Module 2: C# 3.0 Language Enhancements (Material)

MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS

22

public string Name { get; set; }

public string Company { get; set; }

public string Email { get; set; }

public Student()

{

}

public override string ToString()

{

return Name;

}

}

public static class Extensions

{

public static void Print (this string str)

{

Console.WriteLine(str);

}

public static void Print(this List<Student> sts)

{

foreach (var st in sts)

{

Console.WriteLine(st.ToString());

}

}

public static void PrintInformation(this List<Student> sts)

{

string strLine = "{0} In Company {1} with Reg ID {2}";

Console.WriteLine("Students Information:");

Console.WriteLine("=====================");

foreach (var st in sts)

{

Console.WriteLine(strLine,st.Name,st.Company,st.RegID);

}

}

public static void PrintEmails(this List<Student> sts)

{

string strLine = "Name: {0} Email: {1}";

Console.WriteLine("Students Emails:");

Console.WriteLine("=====================");

foreach (var st in sts)

{

Console.WriteLine(strLine, st.Name, st.Email);

}

}

}

class Module02Lab04

{

static void Main(string[] args)

{

var Students = new List<Student>

{

Page 23: Module 2: C# 3.0 Language Enhancements (Material)

MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS

23

new Student { RegID = 1, Company = "SevenSeas",

Email = "[email protected]", Name = "Muhannad"},

new Student { RegID = 2, Company = "Dimensions",

Email = "Mohamed@EastMed", Name = "Mohamed"},

new Student { RegID = 3, Company = "EastMed",

Email = "Osama", Name = "Osama"},

new Student { RegID = 4, Company = "SharpMinds",

Email = "[email protected]", Name = "Ahmed"},

new Student { RegID = 5, Company = "LeadingPoints",

Email = "[email protected]", Name = "Omar"}

};

Console.WriteLine("Students Names:");

Console.WriteLine("===============");

Students.Print();

Console.WriteLine("Press Any Key To Continue...");

Console.ReadKey();

Students.PrintInformation();

Console.WriteLine("Press Any Key To Continue...");

Console.ReadKey();

Students.PrintEmails();

Console.WriteLine("Press Any Key To Continue...");

Console.ReadKey();

}

}

}

15. Click Start on the Debug menu or press F5 to run the code.

Page 24: Module 2: C# 3.0 Language Enhancements (Material)

MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS

24

Lambda Expressions

Lambda Expressions Overview:

Lambda Expressions are the natural evolution of writing functions as expressions from

Delegates in C# 1.0 to Anonymous methods in C# 2.0 to the new technique in C# 3.0 the

Lambda expression, which can be used in expression context instead of writing it the regular

method body with a name.

The following example illustrates how to write lambda expressions:

sts = Students.FindAll(s => s.Company == "Microsoft");

Lambda expression must be written in the left side of the statement, and it consists of two

sides separated by the lambda operator => “goes to”, the left side specifies the parameters if

any, and the right side holds the statement block or the expression.

Lambda Expressions Limitations:

The following limitations must be considered while writing the lambda expressions:

1. It can be only used as a part of statement.

2. The lambda expression does not have a name.

3. Lambda expression cannot contain a goto statement, break statement, or continue

statement whose target is outside the body.

Page 25: Module 2: C# 3.0 Language Enhancements (Material)

MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS

25

Lab 5: Writing Expression Methods

After completing this lab, you will be able to:

Writing lambda expressions

Using the Lambda expressions.

Understanding the different in writing expressions using delegates, anonymous methods,

and lambda expressions.

Implementing and using extension methods

1. On the File menu in Visual Studio 2008, point to New and then click Project.

2. In the New Project dialog box, select a language, and then select Windows in the

Project Types box.

3. In the Templates box, select Console Application.

4. In the Location box, type the path to where to create the application, and then click

OK.

5. In the Visual Studio code editor as the following code:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace GeeksConnected.Module02Lab05

{

Page 26: Module 2: C# 3.0 Language Enhancements (Material)

MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS

26

public class Student

{

public Student()

{

}

public string ID { get; set; }

public string Name { get; set; }

public string Company { get; set; }

}

class Program

{

static void Main(string[] args)

{

List<Student> Students = new List<Student>

{

new Student{Name = "Muhanad", Company = "Microsoft"},

new Student{Name = "Ayman", Company = "Microsoft"},

new Student{Name = "Samer", Company = "Athena"},

new Student{Name = "Ahmad", Company = "Beat"}

};

List<Student> sts = new List<Student>();

// classical programming....

foreach (Student std in Students)

{

if (std.Company == "Microsoft")

{

sts.Add(std);

}

}

PrintStudents(sts);

//C# 1.1 Delegates

sts.Clear();

sts = Students.FindAll(new Predicate<Student>(MicrosoftEmployees));

PrintStudents(sts);

//C# 2.0 Anonymous Method

sts.Clear();

sts = Students.FindAll(delegate(Student st)

{ return st.Company == "Microsoft"; });

PrintStudents(sts);

//C# 3.0: Lambda Expression

sts.Clear();

sts = Students.FindAll(s => s.Company == "Microsoft");

PrintStudents(sts);

}

static bool MicrosoftEmployees(Student st)

{

if (st.Company == "Microsoft")

{

return true;

}

Page 27: Module 2: C# 3.0 Language Enhancements (Material)

MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS

27

else

{

return false;

}

}

static void PrintStudents(List<Student> Students)

{

Console.WriteLine("Microsoft Employees");

Console.WriteLine("===================");

foreach (Student st in Students)

{

Console.WriteLine(st.Name);

}

Console.ReadKey();

}

}

}

6. Click Start on the Debug menu or press F5 to run the code.

Page 28: Module 2: C# 3.0 Language Enhancements (Material)

MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS

28

Summary

In this module, we explored the some of the main enhancements over the C# 3.0 Language,

and we find how this new enhancements can increase the developers productivity, and how

some of it can be work smoothly with the previous versions of the .NET Framework.

Basically C# 3.0 is about productivity, and its created to enable the functionality of the

Language Integrated Query (Linq) in .NET Framework 3.5, C# 3.0 new syntax adds more

functional touch to the language, and allows the developer to become more dynamic and

productive by using some features like Auto-Implemented Properties, Extension Methods,

Initializers, and the Lambda Expression.

In the next module we will learn how all of these enhancements enable the use of .NET

Framework 3.5 LINQ.

Page 29: Module 2: C# 3.0 Language Enhancements (Material)

MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS

29

References

1. Microsoft Site (http://www.microsoft.com)

2. Microsoft Developer Network (http://msdn.microsoft.com)

3. Microsoft Visual Studio 2008 Training Kit

4. Microsoft C# 3.0 Hands-On Lab

5. C# Language Specification Version 3.0

6. Scott Guthrie’s Blog (http://weblogs.asp.net/scottgu/)

7. Scott Hanselman’s Blog(http://www.hanselman.com/)