SlideShare une entreprise Scribd logo
1  sur  29
Télécharger pour lire hors ligne
Visual Studio 2008
  Community Training




              By
         Mohamed Saleh
       mohamedsaleh@live.com
           www.jordev.net
   www.geeksconnected.com/mohamed
MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS




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




2
MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS




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.




3
MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS




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.




4
MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS




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.




5
MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS




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
    {




6
MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS



         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:LabsModule02Lab01binDebug
         and then type ILdasm Module02Lab01.exe, the IL Disassembler will show the
         generated backing fields under the class GeeksConnected.Module02Lab01.Student.




7
MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS




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" };




8
MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS



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.




9
MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS




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
     {




10
MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS



       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
                      {



11
MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS



                                 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




12
MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS



     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:LabsModule02Lab02binDebug
          and then type ILdasm Module02Lab02.exe, the IL Disassembler will show the
          generated initialization instructions under the class Student.




13
MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS




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("...")){…}




14
MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS



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) {…}




15
MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS




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
     {




16
MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS



         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();

             }

         }
     }




17
MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS



     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.




18
MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS




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);
    }
}




19
MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS



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




20
MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS




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; }



21
MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS



           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>
               {



22
MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS



                       new Student { RegID = 1, Company = "SevenSeas",
                                    Email = "Muhannad@SevenSeas.Com", 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 = "Ahmed@SharpMinds.Com", Name = "Ahmed"},
                       new Student { RegID = 5, Company = "LeadingPoints",
                                     Email = "Omar@LeadingPointss.Com", 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.




23
MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS




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.




24
MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS




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
     {



25
MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS



       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;
               }



26
MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS



                   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.




27
MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS




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.




28
MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS




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/)




29

Contenu connexe

Tendances

Decorating code (Research Paper)
Decorating code (Research Paper)Decorating code (Research Paper)
Decorating code (Research Paper)Jenna Pederson
 
Android coding guide lines
Android coding guide linesAndroid coding guide lines
Android coding guide lineslokeshG38
 
01. Introduction to programming with java
01. Introduction to programming with java01. Introduction to programming with java
01. Introduction to programming with javaIntro C# Book
 
Implementing one feature set in two JavaScript engines (Web Engines Hackfest ...
Implementing one feature set in two JavaScript engines (Web Engines Hackfest ...Implementing one feature set in two JavaScript engines (Web Engines Hackfest ...
Implementing one feature set in two JavaScript engines (Web Engines Hackfest ...Igalia
 
Application package
Application packageApplication package
Application packageJAYAARC
 
Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org) (usef...
Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org)  (usef...Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org)  (usef...
Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org) (usef...Make Mannan
 
21. Java High Quality Programming Code
21. Java High Quality Programming Code21. Java High Quality Programming Code
21. Java High Quality Programming CodeIntro C# Book
 
Visula C# Programming Lecture 1
Visula C# Programming Lecture 1Visula C# Programming Lecture 1
Visula C# Programming Lecture 1Abou Bakr Ashraf
 
Overview of CSharp MVC3 and EF4
Overview of CSharp MVC3 and EF4Overview of CSharp MVC3 and EF4
Overview of CSharp MVC3 and EF4Rich Helton
 
Java session04
Java session04Java session04
Java session04Niit Care
 
Big Java Chapter 1
Big Java Chapter 1Big Java Chapter 1
Big Java Chapter 1Maria Joslin
 
Java lab1 manual
Java lab1 manualJava lab1 manual
Java lab1 manualnahalomar
 
Core Java Certification
Core Java CertificationCore Java Certification
Core Java CertificationVskills
 

Tendances (20)

C#.net evolution part 2
C#.net evolution part 2C#.net evolution part 2
C#.net evolution part 2
 
Decorating code (Research Paper)
Decorating code (Research Paper)Decorating code (Research Paper)
Decorating code (Research Paper)
 
Android coding guide lines
Android coding guide linesAndroid coding guide lines
Android coding guide lines
 
01. Introduction to programming with java
01. Introduction to programming with java01. Introduction to programming with java
01. Introduction to programming with java
 
Implementing one feature set in two JavaScript engines (Web Engines Hackfest ...
Implementing one feature set in two JavaScript engines (Web Engines Hackfest ...Implementing one feature set in two JavaScript engines (Web Engines Hackfest ...
Implementing one feature set in two JavaScript engines (Web Engines Hackfest ...
 
Application package
Application packageApplication package
Application package
 
Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org) (usef...
Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org)  (usef...Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org)  (usef...
Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org) (usef...
 
C++ to java
C++ to javaC++ to java
C++ to java
 
21. Java High Quality Programming Code
21. Java High Quality Programming Code21. Java High Quality Programming Code
21. Java High Quality Programming Code
 
Srgoc dotnet_new
Srgoc dotnet_newSrgoc dotnet_new
Srgoc dotnet_new
 
Java Notes
Java Notes Java Notes
Java Notes
 
C# Unit 2 notes
C# Unit 2 notesC# Unit 2 notes
C# Unit 2 notes
 
Visula C# Programming Lecture 1
Visula C# Programming Lecture 1Visula C# Programming Lecture 1
Visula C# Programming Lecture 1
 
Overview of CSharp MVC3 and EF4
Overview of CSharp MVC3 and EF4Overview of CSharp MVC3 and EF4
Overview of CSharp MVC3 and EF4
 
Java session04
Java session04Java session04
Java session04
 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
 
Big Java Chapter 1
Big Java Chapter 1Big Java Chapter 1
Big Java Chapter 1
 
Introduction to CDI
Introduction to CDIIntroduction to CDI
Introduction to CDI
 
Java lab1 manual
Java lab1 manualJava lab1 manual
Java lab1 manual
 
Core Java Certification
Core Java CertificationCore Java Certification
Core Java Certification
 

En vedette

Module 3: Introduction to LINQ (Material)
Module 3: Introduction to LINQ (Material)Module 3: Introduction to LINQ (Material)
Module 3: Introduction to LINQ (Material)Mohamed Saleh
 
Module 4: Introduction to ASP.NET 3.5 (Material)
Module 4: Introduction to ASP.NET 3.5 (Material)Module 4: Introduction to ASP.NET 3.5 (Material)
Module 4: Introduction to ASP.NET 3.5 (Material)Mohamed Saleh
 
Facebook Presentation
Facebook  PresentationFacebook  Presentation
Facebook Presentationmelover123
 
Predictably Irrational Customers
Predictably Irrational CustomersPredictably Irrational Customers
Predictably Irrational CustomersEric Siegmann
 
E Learning Catalog - Servers, VS 2005, etc
E Learning Catalog  - Servers, VS 2005, etcE Learning Catalog  - Servers, VS 2005, etc
E Learning Catalog - Servers, VS 2005, etcprasad_lk
 

En vedette (9)

Oct 2
Oct 2Oct 2
Oct 2
 
Prezentacia
PrezentaciaPrezentacia
Prezentacia
 
Module 3: Introduction to LINQ (Material)
Module 3: Introduction to LINQ (Material)Module 3: Introduction to LINQ (Material)
Module 3: Introduction to LINQ (Material)
 
November
NovemberNovember
November
 
Obamas Mother
Obamas MotherObamas Mother
Obamas Mother
 
Module 4: Introduction to ASP.NET 3.5 (Material)
Module 4: Introduction to ASP.NET 3.5 (Material)Module 4: Introduction to ASP.NET 3.5 (Material)
Module 4: Introduction to ASP.NET 3.5 (Material)
 
Facebook Presentation
Facebook  PresentationFacebook  Presentation
Facebook Presentation
 
Predictably Irrational Customers
Predictably Irrational CustomersPredictably Irrational Customers
Predictably Irrational Customers
 
E Learning Catalog - Servers, VS 2005, etc
E Learning Catalog  - Servers, VS 2005, etcE Learning Catalog  - Servers, VS 2005, etc
E Learning Catalog - Servers, VS 2005, etc
 

Similaire à Module 2: C# 3.0 Language Enhancements (Material)

Module 2: C# 3.0 Language Enhancements (Slides)
Module 2: C# 3.0 Language Enhancements (Slides)Module 2: C# 3.0 Language Enhancements (Slides)
Module 2: C# 3.0 Language Enhancements (Slides)Mohamed Saleh
 
Object-oriented programming (OOP) with Complete understanding modules
Object-oriented programming (OOP) with Complete understanding modulesObject-oriented programming (OOP) with Complete understanding modules
Object-oriented programming (OOP) with Complete understanding modulesDurgesh Singh
 
01. introduction to-programming
01. introduction to-programming01. introduction to-programming
01. introduction to-programmingStoian Kirov
 
Java programming concept
Java programming conceptJava programming concept
Java programming conceptSanjay Gunjal
 
Use Eclipse technologies to build a modern embedded IDE
Use Eclipse technologies to build a modern embedded IDEUse Eclipse technologies to build a modern embedded IDE
Use Eclipse technologies to build a modern embedded IDEBenjamin Cabé
 
Diving into VS 2015 Day2
Diving into VS 2015 Day2Diving into VS 2015 Day2
Diving into VS 2015 Day2Akhil Mittal
 
Stopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under TestStopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under TestSeb Rose
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfoliomwillmer
 
01 Introduction to programming
01 Introduction to programming01 Introduction to programming
01 Introduction to programmingmaznabili
 
2-Vb.net Basic Concepts and structure of .net code.pptx
2-Vb.net Basic Concepts and structure of .net code.pptx2-Vb.net Basic Concepts and structure of .net code.pptx
2-Vb.net Basic Concepts and structure of .net code.pptxUsama182938
 
Lecture-1&2.pdf Visual Programming C# .net framework
Lecture-1&2.pdf Visual Programming C# .net frameworkLecture-1&2.pdf Visual Programming C# .net framework
Lecture-1&2.pdf Visual Programming C# .net frameworkAbdullahNadeem78
 
Mobile Worshop Lab guide
Mobile Worshop Lab guideMobile Worshop Lab guide
Mobile Worshop Lab guideMan Chan
 
C# Tutorial MSM_Murach chapter-15-slides
C# Tutorial MSM_Murach chapter-15-slidesC# Tutorial MSM_Murach chapter-15-slides
C# Tutorial MSM_Murach chapter-15-slidesSami Mut
 

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

Module 2: C# 3.0 Language Enhancements (Slides)
Module 2: C# 3.0 Language Enhancements (Slides)Module 2: C# 3.0 Language Enhancements (Slides)
Module 2: C# 3.0 Language Enhancements (Slides)
 
Object-oriented programming (OOP) with Complete understanding modules
Object-oriented programming (OOP) with Complete understanding modulesObject-oriented programming (OOP) with Complete understanding modules
Object-oriented programming (OOP) with Complete understanding modules
 
01. introduction to-programming
01. introduction to-programming01. introduction to-programming
01. introduction to-programming
 
Java programming concept
Java programming conceptJava programming concept
Java programming concept
 
C# p3
C# p3C# p3
C# p3
 
What's New in Visual Studio 2008
What's New in Visual Studio 2008What's New in Visual Studio 2008
What's New in Visual Studio 2008
 
Use Eclipse technologies to build a modern embedded IDE
Use Eclipse technologies to build a modern embedded IDEUse Eclipse technologies to build a modern embedded IDE
Use Eclipse technologies to build a modern embedded IDE
 
Diving into VS 2015 Day2
Diving into VS 2015 Day2Diving into VS 2015 Day2
Diving into VS 2015 Day2
 
Stopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under TestStopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under Test
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfolio
 
Cheat-sheet_Koin_2023.pdf
Cheat-sheet_Koin_2023.pdfCheat-sheet_Koin_2023.pdf
Cheat-sheet_Koin_2023.pdf
 
Design patterns
Design patternsDesign patterns
Design patterns
 
01 Introduction to programming
01 Introduction to programming01 Introduction to programming
01 Introduction to programming
 
2-Vb.net Basic Concepts and structure of .net code.pptx
2-Vb.net Basic Concepts and structure of .net code.pptx2-Vb.net Basic Concepts and structure of .net code.pptx
2-Vb.net Basic Concepts and structure of .net code.pptx
 
Readme
ReadmeReadme
Readme
 
Lecture-1&2.pdf Visual Programming C# .net framework
Lecture-1&2.pdf Visual Programming C# .net frameworkLecture-1&2.pdf Visual Programming C# .net framework
Lecture-1&2.pdf Visual Programming C# .net framework
 
Introduction to Programming Lesson 01
Introduction to Programming Lesson 01Introduction to Programming Lesson 01
Introduction to Programming Lesson 01
 
Vb6.0 intro
Vb6.0 introVb6.0 intro
Vb6.0 intro
 
Mobile Worshop Lab guide
Mobile Worshop Lab guideMobile Worshop Lab guide
Mobile Worshop Lab guide
 
C# Tutorial MSM_Murach chapter-15-slides
C# Tutorial MSM_Murach chapter-15-slidesC# Tutorial MSM_Murach chapter-15-slides
C# Tutorial MSM_Murach chapter-15-slides
 

Dernier

Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKJago de Vreede
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfOverkill Security
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 

Dernier (20)

Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 

Module 2: C# 3.0 Language Enhancements (Material)

  • 1. Visual Studio 2008 Community Training By Mohamed Saleh mohamedsaleh@live.com www.jordev.net www.geeksconnected.com/mohamed
  • 2. MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS 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 2
  • 3. MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS 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. 3
  • 4. MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS 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. 4
  • 5. MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS 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. 5
  • 6. MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS 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 { 6
  • 7. MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS 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:LabsModule02Lab01binDebug and then type ILdasm Module02Lab01.exe, the IL Disassembler will show the generated backing fields under the class GeeksConnected.Module02Lab01.Student. 7
  • 8. MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS 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" }; 8
  • 9. MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS 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. 9
  • 10. MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS 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 { 10
  • 11. MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS 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 { 11
  • 12. MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS 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 12
  • 13. MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS 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:LabsModule02Lab02binDebug and then type ILdasm Module02Lab02.exe, the IL Disassembler will show the generated initialization instructions under the class Student. 13
  • 14. MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS 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("...")){…} 14
  • 15. MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS 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) {…} 15
  • 16. MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS 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 { 16
  • 17. MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS 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(); } } } 17
  • 18. MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS 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. 18
  • 19. MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS 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); } } 19
  • 20. MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS 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 20
  • 21. MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS 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; } 21
  • 22. MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS 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> { 22
  • 23. MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS new Student { RegID = 1, Company = "SevenSeas", Email = "Muhannad@SevenSeas.Com", 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 = "Ahmed@SharpMinds.Com", Name = "Ahmed"}, new Student { RegID = 5, Company = "LeadingPoints", Email = "Omar@LeadingPointss.Com", 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. 23
  • 24. MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS 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. 24
  • 25. MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS 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 { 25
  • 26. MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS 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; } 26
  • 27. MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS 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. 27
  • 28. MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS 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. 28
  • 29. MODULE 2: C# 3.0 LANGUAGE ENHANCEMENTS 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/) 29