SlideShare a Scribd company logo
1 of 26
Download to read offline
C# 3.0 Language Innovations
                                                    Query
                 var CommonWords =                  expressions
                   from w in wordOccurances
                   where w.Count > 2
Local variable     select new { f.Name, w.Word, W.Count };
type inference

                                 Lambda
                                 expressions
                 var CommonWords =
                   wordOccurances
                   .Where(w => w.Count > 2)
                   .Select(w => new {f.Name, w.Word, W.Count });
Extension
methods            Anonymous                    Object
                   types                        initializers
                                                                  1
Lambda Expressions
 public delegate bool Predicate<T>(T obj);

 public class List<T>
 {                                                 Statement
    public List<T> FindAll(Predicate<T> test) { … } context
   Explicitly
    … typed
 }                                                          Implicitly
       List<Customer> customers =                            typed
       GetCustomerList();
   List<Customer> x = customers.FindAll(                        Expression
       delegate(Customer c) { return c.State == "WA"; }           context
   );


  List<Customer> x = customers.FindAll(c => c.State == "WA");




                                                                             2
Lambda Expressions
 public delegate T Func<T>();
 public delegate T Func<A0, T>(A0 arg0);
 public delegate T Func<A0, A1, T>(A0 arg0, A1
 arg1);
 …
 Func<Customer, bool> test = c => c.State == "WA";

 double factor = 2.0;
 Func<double, double> f = x => x * factor;

 Func<int, int, int> f = (x, y) => x * y;

 Func<int, int, int> comparer =
   (int x, int y) => {
      if (x > y) return 1;
      if (x < y) return -1;
      return 0;
   };
                                                     3
Queries Through APIs
                                       Query operators
                                       are just methods
 public class List<T>
 {
   public List<T> Where(Func<T, bool> predicate) { … }
   public List<S> Select<S>(Func<T, S> selector) { … }
   …
 }                                                        Methods compose
                                                           to form queries
       List<Customer> customers = GetCustomerList();

   List<string> contacts =
      customers.Where(c => c.State == "WA").Select(c =>
   c.Name);
 But what about
  other types?     Declare operators
                    in all collections?               Type inference
                                                      figures out <S>
             What about
               arrays?

                                                                             4
Queries Through APIs
                                            Query operators
                                           are static methods
 public static class Sequence
 {
   public static IEnumerable<T> Where<T>(IEnumerable<T> source,
      Func<T, bool> predicate) { … }

   public static IEnumerable<S> Select<T, S>(IEnumerable<T> source,
     Func<T, S> selector) { … }
   …
 }                                                            Huh?
          Customer[] customers = GetCustomerArray();

      IEnumerable<string> contacts = Sequence.Select(
          Sequence.Where(customers, c => c.State == "WA"),
          c => c.Name);


                                   Want methods on
                                   IEnumerable<T>

                                                                      5
Extension Methods
class Customer { public string Name; }

Customer[ ] c = new Customer[1];

c._


              Huh ?!!?!




                                         6
Extension Methods
                                                    Extension
 namespace System.Query                             methods
 {
   public static class Sequence
   {
     public static IEnumerable<T> Where<T>(this IEnumerable<T> source,
        Func<T, bool> predicate) { … }

      public static IEnumerable<S> Select<T, S>(this IEnumerable<T>
 source,                                                  obj.Foo(x, y)
         Func<T, S> selector) { … }     Brings                 
      …                             extensions into     XXX.Foo(obj, x, y)
   }                                    scope
 }     using System.Query;

  IEnumerable<string> contacts =
    customers.Where(c => c.State == "WA").Select(c =>
  c.Name);

                  IntelliSense!

                                                                             7
Extension Methods


public static class MyExtensions
{
   public static IEnumerable<T> Where<T>(
                this IEnumerable<T> source,
                Func<T, bool> predicate)
   {
      foreach (T item in source)
        if (predicate(item))
          yield return item;
    }
  }


                                              8
Extension Methods
                                  Method is named
                                      ‘Where’


public static class MyExtensions
{
   public static IEnumerable<T> Where<T>(
                this IEnumerable<T> source,
                Func<T, bool> predicate)
   {
      foreach (T item in source)
        if (predicate(item))
          yield return item;
    }
  }


                                                    9
Extension Methods
                                  Method is named
                                      ‘Where’


public static class MyExtensions                     Method extends
{                                                    objects of type
                                                    IEnumerable<T>
   public static IEnumerable<T> Where<T>(
                this IEnumerable<T> source,
                Func<T, bool> predicate)
   {
      foreach (T item in source)
        if (predicate(item))
          yield return item;
    }
  }


                                                                   10
Extension Methods
                                       Method is named
                                           ‘Where’


public static class MyExtensions                           Method extends
{                                                          objects of type
                                                          IEnumerable<T>
   public static IEnumerable<T> Where<T>(
                this IEnumerable<T> source,
                Func<T, bool> predicate)
   {
      foreach (T item in source)
        if (predicate(item))
          yield return item;             Implementation
    }
  }


                                                                         11
Extension Methods
                                        Method is named
                                            ‘Where’


public static class MyExtensions                           Method extends
{                                                          objects of type
                                                          IEnumerable<T>
   public static IEnumerable<T> Where<T>(
                this IEnumerable<T> source,
                Func<T, bool> predicate)
                                                          Signature of the
   {                                                    predicate parameter
      foreach (T item in source)
        if (predicate(item))
          yield return item;             Implementation
    }
  }


                                                                         12
Extension Methods
                                        Method is named
                                            ‘Where’


public static class MyExtensions                           Method extends
{                                                          objects of type
                                                          IEnumerable<T>
   public static IEnumerable<T> Where<T>(
                this IEnumerable<T> source,
                Func<T, bool> predicate)
                                                          Signature of the
   {                                                    predicate parameter
      foreach (T item in source)
        if (predicate(item))
          yield return item;             Implementation
    }
  } string[] names = { "Burke", "Connor", "Frank“ };
   IEnumerable<string> expr = MyExtensions.Where(names,
                            s => s.Length < 6);
                                                                         13
Extension Methods
                                        Method is named
                                            ‘Where’
[System.Runtime.CompilerServices.Extension]
public static class MyExtensions                           Method extends
{                                                          objects of type
                                                          IEnumerable<T>
   public static IEnumerable<T> Where<T>(
                this IEnumerable<T> source,
                Func<T, bool> predicate)
                                                          Signature of the
   {                                                    predicate parameter
      foreach (T item in source)
        if (predicate(item))
          yield return item;             Implementation
    }
  } string[] names = { "Burke", "Connor", "Frank“ };
   IEnumerable<string> expr = names.Where(names,
                            s => s.Length < 6);
                                                                         14
Anonymous Types
 public class Customer
 {
   public string Name;
   public Address Address;         public class Contact
   public string Phone;            {        class ???
   public List<Order> Orders;        public{string Name;
   …                                 public string Phone; Name;
                                               public string
 }                                 }           public string Phone;
Customer c = GetCustomer(…);                }
Contact x = new Contact { Name = c.Name, Phone = c.Phone };

Customer c = GetCustomer(…);
var x = new { Name = c.Name, Phone = c.Phone };

                                              Projection style
Customer c = GetCustomer(…);                     initializer
var x = new { c.Name, c.Phone };


                                                                      15
Anonymous Types
       var contacts =
         from c in customers
         where c.State == "WA"
         select new { c.Name, c.Phone };    class ???
                                            {
        IEnumerable<???>                       public string Name;
                                               public string Phone;
                                            }
       var contacts =
         customers.
         .Where(c => c.State == "WA“)
         .Select(c => new { c.Name, c.Phone });
 ???

       foreach (var c in contacts) {
          Console.WriteLine(c.Name);
          Console.WriteLine(c.Phone);
       }

                                                                      16
Object Initializers
 public class Point
 {
   private int x, y;

     public int X { get { return x; } set { x = value; } }   Field or property
     public int Y { get { return y; } set { y = value; } }     assignments
 }


               Point a = new Point { X = 0, Y = 1 };




               Point a = new Point();
               a.X = 0;
               a.Y = 1;



                                                                                 17
Object Initializers
                                              Embedded
 public class Rectangle                        objects
 {
   private Point p1 = new Point();
   private Point p2 = new Point();                Read-only
                                                  properties
     public Point P1 { get { return p1; } }
     public Point P2 { get { return p2; } }
 }
            Rectangle r = new Rectangle {
               P1 = { X = 0, Y = 1 },
               P2 = { X = 2, Y = 3 }          No “new Point”
            };


            Rectangle r = new Rectangle();
            r.P1.X = 0;
            r.P1.Y = 1;
            r.P2.X = 2;
            r.P2.Y = 3;

                                                               18
Collection Initializers
                                     Must implement
                                     ICollection<T>


 List<int> powers = new List<int> { 1, 10, 100, 1000,
 10000 };
                      List<int> powers = new List<int>();
                      powers.Add(1);
                      powers.Add(10);
                      powers.Add(100);
                      powers.Add(1000);
                      powers.Add(10000);




                                                            19
Collection Initializers
 public class Contact
 {
   private string name;
   private List<string> phoneNumbers = new List<string>();

     public string Name { get { return name; } set { name = value; } }
     public List<string> PhoneNumbers { get { return phoneNumbers; } }
 }
         List<Contact> contacts = new List<Contact> {
            new Contact {
               Name = "Chris Smith",
               PhoneNumbers = { "206-555-0101", "425-882-8080" }
            },
            new Contact {
               Name = "Bob Harris",
               PhoneNumbers = { "650-555-0199" }
            }
         };

                                                                         20
Local Variable Type Inference
   int i = 5;
   string s = "Hello";
   double d = 1.0;
   int[] numbers = new int[] {1, 2, 3};
   Dictionary<int,Order> orders = new Dictionary<int,Order>();


   var i = 5;
   var s = "Hello";
   var d = 1.0;
   var numbers = new int[] {1, 2, 3};
   var orders = new Dictionary<int,Order>();


      “var” means same
       type as initializer


                                                                 21
Expression Trees
 public class Northwind: DataContext
 {
   public Table<Customer> Customers;
   public Table<Order> Orders;                        How does this
   …                                                  get remoted?
 }
    Northwind db = new Northwind(…);
    var query = from c in db.Customers where c.State == "WA" select c;

   Northwind db = new Northwind(…);                      Method asks for
   var query = db.Customers.Where(c => c.State ==        expression tree
   "WA");
 public class Table<T>: IEnumerable<T>
 {
   public Table<T> Where(Expression<Func<T, bool>> predicate);
   …
 }
                                     System.Expressions.
                                       Expression<T>
                                                                           22
Expression Trees
 Code as Data
              Func<Customer, bool> test = c => c.State == "WA";


  Expression<Func<Customer, bool>> test = c => c.State == "WA";


  ParameterExpression c =
     Expression.Parameter(typeof(Customer), "c");
  Expression expr =
     Expression.EQ(
        Expression.Property(c,
  typeof(Customer).GetProperty("State")),
        Expression.Constant("WA")
     );
  Expression<Func<Customer, bool>> test =
     Expression.Lambda<Func<Customer, bool>>(expr, c);

                                                                  23
Query Expressions
  Language integrated query syntax

                            Starts with
                              from          Zero or more
                                           from or where
from id in source
{ from id in source | where condition }         Optional
[ orderby ordering, ordering, … ]               orderby
select expr | group expr by key
[ into id query ]                         Ends with select
                         Optional into      or group by
                         continuation


                                                             24
Query Expressions
 Queries translate to method invocations
   Where, Select, SelectMany, OrderBy, GroupBy

    from c in customers
    where c.State == "WA"
    select new { c.Name, c.Phone };


    customers
    .Where(c => c.State == "WA")
    .Select(c => new { c.Name, c.Phone });

                                             25
C# 3.0 Language Innovations
 Lambda expressions            c => c.Name


 Extension methods          static void Dump(this object o);


 Local variable type inference               var x = 5;

 Object initializers     new Point { x = 1, y = 2 }

 Anonymous types                 new { c.Name,
                                 c.Phone }
 Query expressions
                          from … where …
 Expression trees         select

                       Expression<T>
                                                               26

More Related Content

What's hot

The Ring programming language version 1.5.2 book - Part 32 of 181
The Ring programming language version 1.5.2 book - Part 32 of 181The Ring programming language version 1.5.2 book - Part 32 of 181
The Ring programming language version 1.5.2 book - Part 32 of 181Mahmoud Samir Fayed
 
Modul Praktek Java OOP
Modul Praktek Java OOP Modul Praktek Java OOP
Modul Praktek Java OOP Zaenal Arifin
 
The Ring programming language version 1.5 book - Part 6 of 31
The Ring programming language version 1.5 book - Part 6 of 31The Ring programming language version 1.5 book - Part 6 of 31
The Ring programming language version 1.5 book - Part 6 of 31Mahmoud Samir Fayed
 
The Ring programming language version 1.5.4 book - Part 33 of 185
The Ring programming language version 1.5.4 book - Part 33 of 185The Ring programming language version 1.5.4 book - Part 33 of 185
The Ring programming language version 1.5.4 book - Part 33 of 185Mahmoud Samir Fayed
 
Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8RichardWarburton
 
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...tdc-globalcode
 
The Ring programming language version 1.4.1 book - Part 9 of 31
The Ring programming language version 1.4.1 book - Part 9 of 31The Ring programming language version 1.4.1 book - Part 9 of 31
The Ring programming language version 1.4.1 book - Part 9 of 31Mahmoud Samir Fayed
 
The Ring programming language version 1.3 book - Part 24 of 88
The Ring programming language version 1.3 book - Part 24 of 88The Ring programming language version 1.3 book - Part 24 of 88
The Ring programming language version 1.3 book - Part 24 of 88Mahmoud Samir Fayed
 
Programming Java - Lection 04 - Generics and Lambdas - Lavrentyev Fedor
Programming Java - Lection 04 - Generics and Lambdas - Lavrentyev FedorProgramming Java - Lection 04 - Generics and Lambdas - Lavrentyev Fedor
Programming Java - Lection 04 - Generics and Lambdas - Lavrentyev FedorFedor Lavrentyev
 
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDBTDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDBtdc-globalcode
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsMuhammadTalha436
 
The Ring programming language version 1.5.1 book - Part 31 of 180
The Ring programming language version 1.5.1 book - Part 31 of 180The Ring programming language version 1.5.1 book - Part 31 of 180
The Ring programming language version 1.5.1 book - Part 31 of 180Mahmoud Samir Fayed
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side JavascriptJulie Iskander
 
The Ring programming language version 1.5.3 book - Part 31 of 184
The Ring programming language version 1.5.3 book - Part 31 of 184The Ring programming language version 1.5.3 book - Part 31 of 184
The Ring programming language version 1.5.3 book - Part 31 of 184Mahmoud Samir Fayed
 
OCP Java SE 8 Exam - Sample Questions - Lambda Expressions
OCP Java SE 8 Exam - Sample Questions - Lambda Expressions OCP Java SE 8 Exam - Sample Questions - Lambda Expressions
OCP Java SE 8 Exam - Sample Questions - Lambda Expressions Ganesh Samarthyam
 
C# Summer course - Lecture 3
C# Summer course - Lecture 3C# Summer course - Lecture 3
C# Summer course - Lecture 3mohamedsamyali
 
The Ring programming language version 1.7 book - Part 36 of 196
The Ring programming language version 1.7 book - Part 36 of 196The Ring programming language version 1.7 book - Part 36 of 196
The Ring programming language version 1.7 book - Part 36 of 196Mahmoud Samir Fayed
 
3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в JavaDEVTYPE
 

What's hot (20)

Oop objects_classes
Oop objects_classesOop objects_classes
Oop objects_classes
 
The Ring programming language version 1.5.2 book - Part 32 of 181
The Ring programming language version 1.5.2 book - Part 32 of 181The Ring programming language version 1.5.2 book - Part 32 of 181
The Ring programming language version 1.5.2 book - Part 32 of 181
 
Modul Praktek Java OOP
Modul Praktek Java OOP Modul Praktek Java OOP
Modul Praktek Java OOP
 
The Ring programming language version 1.5 book - Part 6 of 31
The Ring programming language version 1.5 book - Part 6 of 31The Ring programming language version 1.5 book - Part 6 of 31
The Ring programming language version 1.5 book - Part 6 of 31
 
The Ring programming language version 1.5.4 book - Part 33 of 185
The Ring programming language version 1.5.4 book - Part 33 of 185The Ring programming language version 1.5.4 book - Part 33 of 185
The Ring programming language version 1.5.4 book - Part 33 of 185
 
Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8
 
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
 
The Ring programming language version 1.4.1 book - Part 9 of 31
The Ring programming language version 1.4.1 book - Part 9 of 31The Ring programming language version 1.4.1 book - Part 9 of 31
The Ring programming language version 1.4.1 book - Part 9 of 31
 
The Ring programming language version 1.3 book - Part 24 of 88
The Ring programming language version 1.3 book - Part 24 of 88The Ring programming language version 1.3 book - Part 24 of 88
The Ring programming language version 1.3 book - Part 24 of 88
 
Programming Java - Lection 04 - Generics and Lambdas - Lavrentyev Fedor
Programming Java - Lection 04 - Generics and Lambdas - Lavrentyev FedorProgramming Java - Lection 04 - Generics and Lambdas - Lavrentyev Fedor
Programming Java - Lection 04 - Generics and Lambdas - Lavrentyev Fedor
 
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDBTDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ Exams
 
The Ring programming language version 1.5.1 book - Part 31 of 180
The Ring programming language version 1.5.1 book - Part 31 of 180The Ring programming language version 1.5.1 book - Part 31 of 180
The Ring programming language version 1.5.1 book - Part 31 of 180
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
Java generics
Java genericsJava generics
Java generics
 
The Ring programming language version 1.5.3 book - Part 31 of 184
The Ring programming language version 1.5.3 book - Part 31 of 184The Ring programming language version 1.5.3 book - Part 31 of 184
The Ring programming language version 1.5.3 book - Part 31 of 184
 
OCP Java SE 8 Exam - Sample Questions - Lambda Expressions
OCP Java SE 8 Exam - Sample Questions - Lambda Expressions OCP Java SE 8 Exam - Sample Questions - Lambda Expressions
OCP Java SE 8 Exam - Sample Questions - Lambda Expressions
 
C# Summer course - Lecture 3
C# Summer course - Lecture 3C# Summer course - Lecture 3
C# Summer course - Lecture 3
 
The Ring programming language version 1.7 book - Part 36 of 196
The Ring programming language version 1.7 book - Part 36 of 196The Ring programming language version 1.7 book - Part 36 of 196
The Ring programming language version 1.7 book - Part 36 of 196
 
3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java
 

Viewers also liked

Quy trinh sx mu cua cty cao su dong phu binh phuoc
Quy trinh sx mu cua cty cao su dong phu binh phuocQuy trinh sx mu cua cty cao su dong phu binh phuoc
Quy trinh sx mu cua cty cao su dong phu binh phuocHung Pham Thai
 
Donald j trump_trump_the_art_of_the_deal.thegioiebook.com
Donald j trump_trump_the_art_of_the_deal.thegioiebook.comDonald j trump_trump_the_art_of_the_deal.thegioiebook.com
Donald j trump_trump_the_art_of_the_deal.thegioiebook.comHung Pham Thai
 
San sustainable agriculture standard april 2009
San sustainable agriculture standard april 2009San sustainable agriculture standard april 2009
San sustainable agriculture standard april 2009Hung Pham Thai
 
Vt utz coc_coffee_v2009
Vt utz coc_coffee_v2009Vt utz coc_coffee_v2009
Vt utz coc_coffee_v2009Hung Pham Thai
 
Ung dung excel trong kinh te
Ung dung excel trong kinh teUng dung excel trong kinh te
Ung dung excel trong kinh teHung Pham Thai
 
Genetic modified-crops-1228274479307533-9
Genetic modified-crops-1228274479307533-9Genetic modified-crops-1228274479307533-9
Genetic modified-crops-1228274479307533-9Hung Pham Thai
 
PHÁO ĐẦU (CHINA CHESS)
PHÁO ĐẦU (CHINA CHESS)PHÁO ĐẦU (CHINA CHESS)
PHÁO ĐẦU (CHINA CHESS)Hung Pham Thai
 
Technology In The Classroom
Technology In The ClassroomTechnology In The Classroom
Technology In The Classroomhales4
 
Banngheo 100329013057-phpapp01
Banngheo 100329013057-phpapp01Banngheo 100329013057-phpapp01
Banngheo 100329013057-phpapp01Hung Pham Thai
 
Dan brown angelsanddemons
Dan brown angelsanddemonsDan brown angelsanddemons
Dan brown angelsanddemonsHung Pham Thai
 
Info Session (F08)
Info Session (F08)Info Session (F08)
Info Session (F08)birney.james
 
Binh phong ma co dien toan tap 2 (china chess)
Binh phong ma co dien toan tap 2 (china chess)Binh phong ma co dien toan tap 2 (china chess)
Binh phong ma co dien toan tap 2 (china chess)Hung Pham Thai
 
Vegetables. growing asparagus in the home garden
Vegetables. growing asparagus in the home gardenVegetables. growing asparagus in the home garden
Vegetables. growing asparagus in the home gardenHung Pham Thai
 
quất trung bì tập 2 (china chess)
quất trung bì tập 2 (china chess)quất trung bì tập 2 (china chess)
quất trung bì tập 2 (china chess)Hung Pham Thai
 
Mr. Thong Presentation Vn 2009
Mr. Thong Presentation Vn 2009Mr. Thong Presentation Vn 2009
Mr. Thong Presentation Vn 2009Hung Pham Thai
 
ông già và biển cả
ông già và  biển cảông già và  biển cả
ông già và biển cảHung Pham Thai
 
Sars update march 2004 vietnamese1ud
Sars update march 2004 vietnamese1udSars update march 2004 vietnamese1ud
Sars update march 2004 vietnamese1udHung Pham Thai
 

Viewers also liked (20)

Quy trinh sx mu cua cty cao su dong phu binh phuoc
Quy trinh sx mu cua cty cao su dong phu binh phuocQuy trinh sx mu cua cty cao su dong phu binh phuoc
Quy trinh sx mu cua cty cao su dong phu binh phuoc
 
Banking K42 2005
Banking K42 2005Banking K42 2005
Banking K42 2005
 
Donald j trump_trump_the_art_of_the_deal.thegioiebook.com
Donald j trump_trump_the_art_of_the_deal.thegioiebook.comDonald j trump_trump_the_art_of_the_deal.thegioiebook.com
Donald j trump_trump_the_art_of_the_deal.thegioiebook.com
 
San sustainable agriculture standard april 2009
San sustainable agriculture standard april 2009San sustainable agriculture standard april 2009
San sustainable agriculture standard april 2009
 
Vt utz coc_coffee_v2009
Vt utz coc_coffee_v2009Vt utz coc_coffee_v2009
Vt utz coc_coffee_v2009
 
Ung dung excel trong kinh te
Ung dung excel trong kinh teUng dung excel trong kinh te
Ung dung excel trong kinh te
 
Genetic modified-crops-1228274479307533-9
Genetic modified-crops-1228274479307533-9Genetic modified-crops-1228274479307533-9
Genetic modified-crops-1228274479307533-9
 
PHÁO ĐẦU (CHINA CHESS)
PHÁO ĐẦU (CHINA CHESS)PHÁO ĐẦU (CHINA CHESS)
PHÁO ĐẦU (CHINA CHESS)
 
Technology In The Classroom
Technology In The ClassroomTechnology In The Classroom
Technology In The Classroom
 
Banngheo 100329013057-phpapp01
Banngheo 100329013057-phpapp01Banngheo 100329013057-phpapp01
Banngheo 100329013057-phpapp01
 
Dan brown angelsanddemons
Dan brown angelsanddemonsDan brown angelsanddemons
Dan brown angelsanddemons
 
Info Session (F08)
Info Session (F08)Info Session (F08)
Info Session (F08)
 
Binh phong ma co dien toan tap 2 (china chess)
Binh phong ma co dien toan tap 2 (china chess)Binh phong ma co dien toan tap 2 (china chess)
Binh phong ma co dien toan tap 2 (china chess)
 
Vegetables. growing asparagus in the home garden
Vegetables. growing asparagus in the home gardenVegetables. growing asparagus in the home garden
Vegetables. growing asparagus in the home garden
 
quất trung bì tập 2 (china chess)
quất trung bì tập 2 (china chess)quất trung bì tập 2 (china chess)
quất trung bì tập 2 (china chess)
 
Mr. Thong Presentation Vn 2009
Mr. Thong Presentation Vn 2009Mr. Thong Presentation Vn 2009
Mr. Thong Presentation Vn 2009
 
Today Is Tuesday
Today Is TuesdayToday Is Tuesday
Today Is Tuesday
 
ông già và biển cả
ông già và  biển cảông già và  biển cả
ông già và biển cả
 
Tcvn 3769 2004
Tcvn 3769 2004Tcvn 3769 2004
Tcvn 3769 2004
 
Sars update march 2004 vietnamese1ud
Sars update march 2004 vietnamese1udSars update march 2004 vietnamese1ud
Sars update march 2004 vietnamese1ud
 

Similar to C# 3.0 Language Innovations

Mixing functional programming approaches in an object oriented language
Mixing functional programming approaches in an object oriented languageMixing functional programming approaches in an object oriented language
Mixing functional programming approaches in an object oriented languageMark Needham
 
Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)Andrew Petryk
 
Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Juan Pablo
 
Whats New In C# 4 0 - NetPonto
Whats New In C# 4 0 - NetPontoWhats New In C# 4 0 - NetPonto
Whats New In C# 4 0 - NetPontoPaulo Morgado
 
Linq and lambda
Linq and lambdaLinq and lambda
Linq and lambdaJohn Walsh
 
devLink - What's New in C# 4?
devLink - What's New in C# 4?devLink - What's New in C# 4?
devLink - What's New in C# 4?Kevin Pilch
 
Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05
Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05
Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05CHOOSE
 
Java8: Language Enhancements
Java8: Language EnhancementsJava8: Language Enhancements
Java8: Language EnhancementsYuriy Bondaruk
 
Get Functional on the CLR: Intro to Functional Programming with F#
Get Functional on the CLR: Intro to Functional Programming with F# Get Functional on the CLR: Intro to Functional Programming with F#
Get Functional on the CLR: Intro to Functional Programming with F# David Alpert
 
Lambda expressions
Lambda expressionsLambda expressions
Lambda expressionsYuriy Seniuk
 
Monadic Comprehensions and Functional Composition with Query Expressions
Monadic Comprehensions and Functional Composition with Query ExpressionsMonadic Comprehensions and Functional Composition with Query Expressions
Monadic Comprehensions and Functional Composition with Query ExpressionsChris Eargle
 

Similar to C# 3.0 Language Innovations (20)

Mixing functional programming approaches in an object oriented language
Mixing functional programming approaches in an object oriented languageMixing functional programming approaches in an object oriented language
Mixing functional programming approaches in an object oriented language
 
Lesson11
Lesson11Lesson11
Lesson11
 
Understanding linq
Understanding linqUnderstanding linq
Understanding linq
 
Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)
 
Linq Introduction
Linq IntroductionLinq Introduction
Linq Introduction
 
Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#
 
Whats New In C# 4 0 - NetPonto
Whats New In C# 4 0 - NetPontoWhats New In C# 4 0 - NetPonto
Whats New In C# 4 0 - NetPonto
 
Generics_RIO.ppt
Generics_RIO.pptGenerics_RIO.ppt
Generics_RIO.ppt
 
Introducción a LINQ
Introducción a LINQIntroducción a LINQ
Introducción a LINQ
 
Linq and lambda
Linq and lambdaLinq and lambda
Linq and lambda
 
devLink - What's New in C# 4?
devLink - What's New in C# 4?devLink - What's New in C# 4?
devLink - What's New in C# 4?
 
Ds lab handouts
Ds lab handoutsDs lab handouts
Ds lab handouts
 
Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05
Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05
Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05
 
Introduction to Linq
Introduction to LinqIntroduction to Linq
Introduction to Linq
 
Java8: Language Enhancements
Java8: Language EnhancementsJava8: Language Enhancements
Java8: Language Enhancements
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
JAVA PROGRAMMING - The Collections Framework
JAVA PROGRAMMING - The Collections Framework JAVA PROGRAMMING - The Collections Framework
JAVA PROGRAMMING - The Collections Framework
 
Get Functional on the CLR: Intro to Functional Programming with F#
Get Functional on the CLR: Intro to Functional Programming with F# Get Functional on the CLR: Intro to Functional Programming with F#
Get Functional on the CLR: Intro to Functional Programming with F#
 
Lambda expressions
Lambda expressionsLambda expressions
Lambda expressions
 
Monadic Comprehensions and Functional Composition with Query Expressions
Monadic Comprehensions and Functional Composition with Query ExpressionsMonadic Comprehensions and Functional Composition with Query Expressions
Monadic Comprehensions and Functional Composition with Query Expressions
 

More from Shahriar Hyder

Effective Communication Skills for Software Engineers
Effective Communication Skills for Software EngineersEffective Communication Skills for Software Engineers
Effective Communication Skills for Software EngineersShahriar Hyder
 
A JavaScript Master Class - From the Wows to the WTFs
A JavaScript Master Class - From the Wows to the WTFsA JavaScript Master Class - From the Wows to the WTFs
A JavaScript Master Class - From the Wows to the WTFsShahriar Hyder
 
Dependency Inversion Principle
Dependency Inversion PrincipleDependency Inversion Principle
Dependency Inversion PrincipleShahriar Hyder
 
Command Design Pattern
Command Design PatternCommand Design Pattern
Command Design PatternShahriar Hyder
 
Taking a Quantum Leap with Html 5 WebSocket
Taking a Quantum Leap with Html 5 WebSocketTaking a Quantum Leap with Html 5 WebSocket
Taking a Quantum Leap with Html 5 WebSocketShahriar Hyder
 
Functional Programming Fundamentals
Functional Programming FundamentalsFunctional Programming Fundamentals
Functional Programming FundamentalsShahriar Hyder
 
Object Relational Mapping with LINQ To SQL
Object Relational Mapping with LINQ To SQLObject Relational Mapping with LINQ To SQL
Object Relational Mapping with LINQ To SQLShahriar Hyder
 

More from Shahriar Hyder (8)

Effective Communication Skills for Software Engineers
Effective Communication Skills for Software EngineersEffective Communication Skills for Software Engineers
Effective Communication Skills for Software Engineers
 
A JavaScript Master Class - From the Wows to the WTFs
A JavaScript Master Class - From the Wows to the WTFsA JavaScript Master Class - From the Wows to the WTFs
A JavaScript Master Class - From the Wows to the WTFs
 
Dependency Inversion Principle
Dependency Inversion PrincipleDependency Inversion Principle
Dependency Inversion Principle
 
Bridge Design Pattern
Bridge Design PatternBridge Design Pattern
Bridge Design Pattern
 
Command Design Pattern
Command Design PatternCommand Design Pattern
Command Design Pattern
 
Taking a Quantum Leap with Html 5 WebSocket
Taking a Quantum Leap with Html 5 WebSocketTaking a Quantum Leap with Html 5 WebSocket
Taking a Quantum Leap with Html 5 WebSocket
 
Functional Programming Fundamentals
Functional Programming FundamentalsFunctional Programming Fundamentals
Functional Programming Fundamentals
 
Object Relational Mapping with LINQ To SQL
Object Relational Mapping with LINQ To SQLObject Relational Mapping with LINQ To SQL
Object Relational Mapping with LINQ To SQL
 

Recently uploaded

A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...Karmanjay Verma
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesBernd Ruecker
 
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)Mark Simos
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesManik S Magar
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkPixlogix Infotech
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Kaya Weers
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...itnewsafrica
 
A Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxA Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxAna-Maria Mihalceanu
 

Recently uploaded (20)

A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architectures
 
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App Framework
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
 
A Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxA Glance At The Java Performance Toolbox
A Glance At The Java Performance Toolbox
 

C# 3.0 Language Innovations

  • 1. C# 3.0 Language Innovations Query var CommonWords = expressions from w in wordOccurances where w.Count > 2 Local variable select new { f.Name, w.Word, W.Count }; type inference Lambda expressions var CommonWords = wordOccurances .Where(w => w.Count > 2) .Select(w => new {f.Name, w.Word, W.Count }); Extension methods Anonymous Object types initializers 1
  • 2. Lambda Expressions public delegate bool Predicate<T>(T obj); public class List<T> { Statement public List<T> FindAll(Predicate<T> test) { … } context Explicitly … typed } Implicitly List<Customer> customers = typed GetCustomerList(); List<Customer> x = customers.FindAll( Expression delegate(Customer c) { return c.State == "WA"; } context ); List<Customer> x = customers.FindAll(c => c.State == "WA"); 2
  • 3. Lambda Expressions public delegate T Func<T>(); public delegate T Func<A0, T>(A0 arg0); public delegate T Func<A0, A1, T>(A0 arg0, A1 arg1); … Func<Customer, bool> test = c => c.State == "WA"; double factor = 2.0; Func<double, double> f = x => x * factor; Func<int, int, int> f = (x, y) => x * y; Func<int, int, int> comparer = (int x, int y) => { if (x > y) return 1; if (x < y) return -1; return 0; }; 3
  • 4. Queries Through APIs Query operators are just methods public class List<T> { public List<T> Where(Func<T, bool> predicate) { … } public List<S> Select<S>(Func<T, S> selector) { … } … } Methods compose to form queries List<Customer> customers = GetCustomerList(); List<string> contacts = customers.Where(c => c.State == "WA").Select(c => c.Name); But what about other types? Declare operators in all collections? Type inference figures out <S> What about arrays? 4
  • 5. Queries Through APIs Query operators are static methods public static class Sequence { public static IEnumerable<T> Where<T>(IEnumerable<T> source, Func<T, bool> predicate) { … } public static IEnumerable<S> Select<T, S>(IEnumerable<T> source, Func<T, S> selector) { … } … } Huh? Customer[] customers = GetCustomerArray(); IEnumerable<string> contacts = Sequence.Select( Sequence.Where(customers, c => c.State == "WA"), c => c.Name); Want methods on IEnumerable<T> 5
  • 6. Extension Methods class Customer { public string Name; } Customer[ ] c = new Customer[1]; c._ Huh ?!!?! 6
  • 7. Extension Methods Extension namespace System.Query methods { public static class Sequence { public static IEnumerable<T> Where<T>(this IEnumerable<T> source, Func<T, bool> predicate) { … } public static IEnumerable<S> Select<T, S>(this IEnumerable<T> source, obj.Foo(x, y) Func<T, S> selector) { … } Brings  … extensions into XXX.Foo(obj, x, y) } scope } using System.Query; IEnumerable<string> contacts = customers.Where(c => c.State == "WA").Select(c => c.Name); IntelliSense! 7
  • 8. Extension Methods public static class MyExtensions { public static IEnumerable<T> Where<T>( this IEnumerable<T> source, Func<T, bool> predicate) { foreach (T item in source) if (predicate(item)) yield return item; } } 8
  • 9. Extension Methods Method is named ‘Where’ public static class MyExtensions { public static IEnumerable<T> Where<T>( this IEnumerable<T> source, Func<T, bool> predicate) { foreach (T item in source) if (predicate(item)) yield return item; } } 9
  • 10. Extension Methods Method is named ‘Where’ public static class MyExtensions Method extends { objects of type IEnumerable<T> public static IEnumerable<T> Where<T>( this IEnumerable<T> source, Func<T, bool> predicate) { foreach (T item in source) if (predicate(item)) yield return item; } } 10
  • 11. Extension Methods Method is named ‘Where’ public static class MyExtensions Method extends { objects of type IEnumerable<T> public static IEnumerable<T> Where<T>( this IEnumerable<T> source, Func<T, bool> predicate) { foreach (T item in source) if (predicate(item)) yield return item; Implementation } } 11
  • 12. Extension Methods Method is named ‘Where’ public static class MyExtensions Method extends { objects of type IEnumerable<T> public static IEnumerable<T> Where<T>( this IEnumerable<T> source, Func<T, bool> predicate) Signature of the { predicate parameter foreach (T item in source) if (predicate(item)) yield return item; Implementation } } 12
  • 13. Extension Methods Method is named ‘Where’ public static class MyExtensions Method extends { objects of type IEnumerable<T> public static IEnumerable<T> Where<T>( this IEnumerable<T> source, Func<T, bool> predicate) Signature of the { predicate parameter foreach (T item in source) if (predicate(item)) yield return item; Implementation } } string[] names = { "Burke", "Connor", "Frank“ }; IEnumerable<string> expr = MyExtensions.Where(names, s => s.Length < 6); 13
  • 14. Extension Methods Method is named ‘Where’ [System.Runtime.CompilerServices.Extension] public static class MyExtensions Method extends { objects of type IEnumerable<T> public static IEnumerable<T> Where<T>( this IEnumerable<T> source, Func<T, bool> predicate) Signature of the { predicate parameter foreach (T item in source) if (predicate(item)) yield return item; Implementation } } string[] names = { "Burke", "Connor", "Frank“ }; IEnumerable<string> expr = names.Where(names, s => s.Length < 6); 14
  • 15. Anonymous Types public class Customer { public string Name; public Address Address; public class Contact public string Phone; { class ??? public List<Order> Orders; public{string Name; … public string Phone; Name; public string } } public string Phone; Customer c = GetCustomer(…); } Contact x = new Contact { Name = c.Name, Phone = c.Phone }; Customer c = GetCustomer(…); var x = new { Name = c.Name, Phone = c.Phone }; Projection style Customer c = GetCustomer(…); initializer var x = new { c.Name, c.Phone }; 15
  • 16. Anonymous Types var contacts = from c in customers where c.State == "WA" select new { c.Name, c.Phone }; class ??? { IEnumerable<???> public string Name; public string Phone; } var contacts = customers. .Where(c => c.State == "WA“) .Select(c => new { c.Name, c.Phone }); ??? foreach (var c in contacts) { Console.WriteLine(c.Name); Console.WriteLine(c.Phone); } 16
  • 17. Object Initializers public class Point { private int x, y; public int X { get { return x; } set { x = value; } } Field or property public int Y { get { return y; } set { y = value; } } assignments } Point a = new Point { X = 0, Y = 1 }; Point a = new Point(); a.X = 0; a.Y = 1; 17
  • 18. Object Initializers Embedded public class Rectangle objects { private Point p1 = new Point(); private Point p2 = new Point(); Read-only properties public Point P1 { get { return p1; } } public Point P2 { get { return p2; } } } Rectangle r = new Rectangle { P1 = { X = 0, Y = 1 }, P2 = { X = 2, Y = 3 } No “new Point” }; Rectangle r = new Rectangle(); r.P1.X = 0; r.P1.Y = 1; r.P2.X = 2; r.P2.Y = 3; 18
  • 19. Collection Initializers Must implement ICollection<T> List<int> powers = new List<int> { 1, 10, 100, 1000, 10000 }; List<int> powers = new List<int>(); powers.Add(1); powers.Add(10); powers.Add(100); powers.Add(1000); powers.Add(10000); 19
  • 20. Collection Initializers public class Contact { private string name; private List<string> phoneNumbers = new List<string>(); public string Name { get { return name; } set { name = value; } } public List<string> PhoneNumbers { get { return phoneNumbers; } } } List<Contact> contacts = new List<Contact> { new Contact { Name = "Chris Smith", PhoneNumbers = { "206-555-0101", "425-882-8080" } }, new Contact { Name = "Bob Harris", PhoneNumbers = { "650-555-0199" } } }; 20
  • 21. Local Variable Type Inference int i = 5; string s = "Hello"; double d = 1.0; int[] numbers = new int[] {1, 2, 3}; Dictionary<int,Order> orders = new Dictionary<int,Order>(); var i = 5; var s = "Hello"; var d = 1.0; var numbers = new int[] {1, 2, 3}; var orders = new Dictionary<int,Order>(); “var” means same type as initializer 21
  • 22. Expression Trees public class Northwind: DataContext { public Table<Customer> Customers; public Table<Order> Orders; How does this … get remoted? } Northwind db = new Northwind(…); var query = from c in db.Customers where c.State == "WA" select c; Northwind db = new Northwind(…); Method asks for var query = db.Customers.Where(c => c.State == expression tree "WA"); public class Table<T>: IEnumerable<T> { public Table<T> Where(Expression<Func<T, bool>> predicate); … } System.Expressions. Expression<T> 22
  • 23. Expression Trees Code as Data Func<Customer, bool> test = c => c.State == "WA"; Expression<Func<Customer, bool>> test = c => c.State == "WA"; ParameterExpression c = Expression.Parameter(typeof(Customer), "c"); Expression expr = Expression.EQ( Expression.Property(c, typeof(Customer).GetProperty("State")), Expression.Constant("WA") ); Expression<Func<Customer, bool>> test = Expression.Lambda<Func<Customer, bool>>(expr, c); 23
  • 24. Query Expressions Language integrated query syntax Starts with from Zero or more from or where from id in source { from id in source | where condition } Optional [ orderby ordering, ordering, … ] orderby select expr | group expr by key [ into id query ] Ends with select Optional into or group by continuation 24
  • 25. Query Expressions Queries translate to method invocations Where, Select, SelectMany, OrderBy, GroupBy from c in customers where c.State == "WA" select new { c.Name, c.Phone }; customers .Where(c => c.State == "WA") .Select(c => new { c.Name, c.Phone }); 25
  • 26. C# 3.0 Language Innovations Lambda expressions c => c.Name Extension methods static void Dump(this object o); Local variable type inference var x = 5; Object initializers new Point { x = 1, y = 2 } Anonymous types new { c.Name, c.Phone } Query expressions from … where … Expression trees select Expression<T> 26