SlideShare une entreprise Scribd logo
1  sur  35
What’s New in Dot net 3.5
•   Automatic Properties
•   Extension Methods
•   Object Initialization
•   Anonymous Types
•   Partial Methods
•   Type Inference
•   LINQ
•   Lambda Expression
•   Query Expression
•   All Together
Language Enhancements + Query
Expressions = LINQ
Language Enhancements consists of
  –   Local Variable Type Inference
  –   Object Initialisers
  –   Anonymous Types
  –   Lambda Expressions
  –   Extension Methods
• No need of private variable
• When no extra logic is required in get and set
• private set is used for making read-only
  property
• prop + double tab is code snippet
public class Product
{
  private string name;
  private decimal price;

    public string Name {
      get { return name; }
      set { name = value; }
    }

    public decimal Price {
      get { return price; }
      set { price = value; }
    }
}
public class Product
{                                             Must have both
  public string Name { get; set; }            get and set
  public decimal Price { get; set; }
}



public class Product
{
  public string Name { get; private set; }
  public decimal Price { get; set; }         Read only
}                                            property
•   Equivalent to calling the static method
•   Can access only public members.
•   Can add methods to other classes
    ◦ any methods (although look static)
    ◦ only from static classes
•   When import a namespace that has extensions, then
    added to classes
    ◦ once imported, called as usual
•   Local methods take precedence
    ◦ first local for normal method, then extension
namespace MyStuff                              Extension
{                                              method
  public static class Extensions
  {
    public static string Concatenate(this IEnumerable<string> strings,
      string separator) {…}
  }
}

                                    Brings extensions into
  using MyStuff;                    scope
                                                             obj.Foo(x, y)
                                                             
string[] names = new string[] { "Axel", "Mia", "Niels" };    XXX.Foo(obj, x, y)
string s = names.Concatenate(", ");

                   IntelliSense!
•   Can initialize fields like attribute fields
    ◦ new C(1, 2, name=“my class”);
    ◦ works if public field or if property with set
    ◦ can be nested (eg. Rectangle with two Points)
•   Collection initializers
    ◦ List<int> digits = new List<int> { 0, 1};
    ◦ Must implement System.Generic.ICollection<T>
•   Object initializers
    ◦ var a = new Point { X = 0, Y = 1 };
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;
Must implement         Must have public
            IEnumerable            Add method


List<int> numbers = new List<int> { 1, 10, 100 };

             List<int> numbers = new
             List<int>();
                                                           Add can take
             numbers.Add(1);
                                                           more than one
             numbers.Add(10);                              parameter
             numbers.Add(100);

    Dictionary<int, string> spellings = new Dictionary<int, string> {
      { 0, "Zero" }, { 1, "One" }, { 2, "Two" }, { 3, "Three" } };
   Type of the variable induced from expression
    ◦ must include initializer
    ◦ can’t be null. Why not?
   What happens if “var” is a class in scope?
   Works in foreach loops
•   var can only be used when a local variable is declared and
    initialized in the same statement; the variable cannot be initialized
    to null literal, because it does not have a type – like lambda
    expressions or method groups. However, it can be initialized with
    an expression that happens to have the value null, as long as the
    expression has a type.
•   var cannot be used on fields in class scope.
•   Variables declared by using var cannot be used in their own
    initialization expression.
    In other words, var v = v++; will result in a compile-time error.
•   Multiple implicitly-typed variables cannot be initialized in the
    same statement.
•   If a type named var is in scope, then we will get a compile-time
    error if we attempt to initialize a local variable with the var
    keyword.
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>();


   “The type on the
   right hand side”
•   var x = new {p1 = 10, p2 = “name”};
    ◦ x is of anonymous type
    ◦ type can’t be referred to by name in program
•   structural type equivalence
    ◦ two anonymous types can be compatible
•   implicitly typed arrays
    ◦ var a = new[] { 1, 10, 100, 1000 };
    ◦ must have consistent types
    ◦ or have implicit conversions
IEnumerable<Contact> phoneListQuery =
  from c in customers
  where c.State == "WA"
  select new Contact { Name = c.Name, Phone = c.Phone };



                    +
           public class Contact
           {
             public string Name;
             public string Phone;
           }
IEnumerable< Contact >                          class Contact
                                                   {
                                                      public string Name;
                                                      public string Phone;
var phoneListQuery =                               }
  from c in customers
  where c.State == "WA"
  select new { Name = c.Name, Phone = c.Phone };

   Contact


     foreach (var entry in phoneListQuery) {
       Console.WriteLine(entry.Name);
       Console.WriteLine(entry.Phone);
     }
•   Partial methods are methods living in partial
    classes which are marked as partial
•   The method must return void.
•   No access modifiers or attributes are allowed.
    Partial methods are implicitly private.
•   Partial methods method hooks, similar to event
    handlers, that developers may decide to implement
    or not.
•   If the developer does not supply an
    implementation, the compiler removes the
    signature at compile time.
partial class A
{
   partial void OnSomethingHappened(string s);
}


// This part can be in a separate file.
partial class A
{
    // Comment out this method and the program
   // will still compile.
  partial void OnSomethingHappened(String s)
  {
     Console.WriteLine("Something happened: {0}", s);
   }
 }
•   Unified programming model for any data
    type/source
•   Collections
•   Database Relational Data
•   XML Files
•   Extendable for anything else
•   Introduce more declarative syntax
•   Data is equivalent to Objects
C# 3.0                  VB 9.0                Others…


                   .NET Language-Integrated Query (LINQ)


                                  LINQ enabled ADO.NET
 LINQ                 LINQ          LINQ           LINQ           LINQ
  To                    to           To             To              to
Objects              Entities       SQL           Dataset         XML




            Objects             Relational Data               XML
•   Syntax based on Extension methods
•   Some Extension methods may be replaced
    by language keywords
    – where, orderby, select, group, …
•   Auxiliary language features in use
    –   Automatic properties
    –   Anonymous types
    –   Implicitly typed local variables
    –   Object initializers
•   Working with collections
    ◦ Any one that implements IEnumerable<T>
•   using System.Linq
•   Generalized function syntax
    ◦    x.x+1
    ◦ in C# 3.0, have x => x + 1
•   From anonymous delegate syntax:
    ◦ delegate(int x) { return x + 1;}
•   Can have implicitly typed variables
•   Can have more than one variable
•   Can have expression or statement body
•   Can be converted to delegate type
    ◦ if parameters and body match
    ◦ delegate R Func<A,R>(A arg);
      Func<int,int> f1 = x => x + 1;
      Func<int,double> f2 = x => x + 1;
      Func<double,int> f3 = x => x + 1;
•   Participate in type inference
•   If expression body, get expression trees
public delegate bool Predicate<T>(T obj);

public class List<T>
{
   public List<T> FindAll(Predicate<T> test)
 {
     List<T> result = new List<T>();
     foreach (T item in this)
        if (test(item)) result.Add(item);
     return result;
   }
   …
}
public class MyClass
{
  public static void Main() {
    List<Customer> customers = GetCustomerList();
    List<Customer> locals =
       customers.FindAll(
          new Predicate<Customer>(StateEqualsWA)
       );
  }

    static bool StateEqualsWA(Customer c) {
      return c.State == "WA";
    }
}
public class MyClass
{
  public static void Main() {
    List<Customer> customers = GetCustomerList();
    List<Customer> locals =
       customers.FindAll(
          delegate(Customer c) { return c.State == "WA"; }
       );
  }
}
public class MyClass
{
  public static void Main() {
    List<Customer> customers = GetCustomerList();
    List<Customer> locals =
       customers.FindAll(c => c.State == "WA");
  }
}

                                Lambda
                                expression
•   Adds querying to language
    ◦ important for interaction with DB
    ◦ but also with built-in data structures
    ◦ leave query planning to data structure designer
•   Implemented using above functionality
    ◦ anonymous types and variables useful
    ◦ lambda expressions make it cleaner.
Starts with
           from
                                   Zero or more
                                   from, join, let, wher
  from id in source                e, or orderby
{ from id in source |
  join id in source on expr equals expr [ into id ] |
  let id = expr |
  where condition |                      Ends with select
                                         or group by
  orderby ordering, ordering, … }
  select expr | group expr by key
[ into id query ]
                         Optional into
                         continuation
   Queries translate to method invocations
    ◦ Where, Join, OrderBy, Select, 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 });
Project     Select <expr>
Filter      Where <expr>, Distinct
Test        Any(<expr>), All(<expr>)
Join        <expr> Join <expr> On <expr> Equals <expr>
Group       Group By <expr>, <expr> Into <expr>, <expr>
            Group Join <decl> On <expr> Equals <expr> Into <expr>
Aggregate   Count(<expr>), Sum(<expr>), Min(<expr>), Max(<expr>),
            Avg(<expr>)
Partition   Skip [ While ] <expr>, Take [ While ] <expr>
Set         Union, Intersect, Except
Order       Order By <expr>, <expr> [ Ascending | Descending ]
var contacts =                        Query
                                                     expressions
                   from c in customers
                   where c.State == "WA"
                   select new { c.Name, c.Phone };
type inference
                                       Lambda
                                     expressions
                 var contacts =
                   customers
                   .Where(c => c.State == "WA")
                   .Select(c => new { c.Name, c.Phone });
 Extension
 methods             Anonymous                           Object
                       types                           initializers
Dot net 3.5 Language Enhancements and LINQ

Contenu connexe

Tendances

Ti1220 Lecture 7: Polymorphism
Ti1220 Lecture 7: PolymorphismTi1220 Lecture 7: Polymorphism
Ti1220 Lecture 7: PolymorphismEelco Visser
 
The Ring programming language version 1.9 book - Part 98 of 210
The Ring programming language version 1.9 book - Part 98 of 210The Ring programming language version 1.9 book - Part 98 of 210
The Ring programming language version 1.9 book - Part 98 of 210Mahmoud Samir Fayed
 
Namespace in C++ Programming Language
Namespace in C++ Programming LanguageNamespace in C++ Programming Language
Namespace in C++ Programming LanguageHimanshu Choudhary
 
The Ring programming language version 1.5.1 book - Part 174 of 180
The Ring programming language version 1.5.1 book - Part 174 of 180 The Ring programming language version 1.5.1 book - Part 174 of 180
The Ring programming language version 1.5.1 book - Part 174 of 180 Mahmoud Samir Fayed
 
On Parameterised Types and Java Generics
On Parameterised Types and Java GenericsOn Parameterised Types and Java Generics
On Parameterised Types and Java GenericsYann-Gaël Guéhéneuc
 
Functions & closures
Functions & closuresFunctions & closures
Functions & closuresKnoldus Inc.
 
Programming in Scala - Lecture Two
Programming in Scala - Lecture TwoProgramming in Scala - Lecture Two
Programming in Scala - Lecture TwoAngelo Corsaro
 
Demystifying functional programming with Scala
Demystifying functional programming with ScalaDemystifying functional programming with Scala
Demystifying functional programming with ScalaDenis
 
Programming in Scala - Lecture One
Programming in Scala - Lecture OneProgramming in Scala - Lecture One
Programming in Scala - Lecture OneAngelo Corsaro
 
Programming in Scala - Lecture Three
Programming in Scala - Lecture ThreeProgramming in Scala - Lecture Three
Programming in Scala - Lecture ThreeAngelo Corsaro
 
Generics in .NET, C++ and Java
Generics in .NET, C++ and JavaGenerics in .NET, C++ and Java
Generics in .NET, C++ and JavaSasha Goldshtein
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With ScalaKnoldus Inc.
 

Tendances (19)

Ti1220 Lecture 7: Polymorphism
Ti1220 Lecture 7: PolymorphismTi1220 Lecture 7: Polymorphism
Ti1220 Lecture 7: Polymorphism
 
The Ring programming language version 1.9 book - Part 98 of 210
The Ring programming language version 1.9 book - Part 98 of 210The Ring programming language version 1.9 book - Part 98 of 210
The Ring programming language version 1.9 book - Part 98 of 210
 
Namespace in C++ Programming Language
Namespace in C++ Programming LanguageNamespace in C++ Programming Language
Namespace in C++ Programming Language
 
Java Generics
Java GenericsJava Generics
Java Generics
 
The Ring programming language version 1.5.1 book - Part 174 of 180
The Ring programming language version 1.5.1 book - Part 174 of 180 The Ring programming language version 1.5.1 book - Part 174 of 180
The Ring programming language version 1.5.1 book - Part 174 of 180
 
On Parameterised Types and Java Generics
On Parameterised Types and Java GenericsOn Parameterised Types and Java Generics
On Parameterised Types and Java Generics
 
Functions & closures
Functions & closuresFunctions & closures
Functions & closures
 
Ruby Programming Assignment Help
Ruby Programming Assignment HelpRuby Programming Assignment Help
Ruby Programming Assignment Help
 
Programming in Scala - Lecture Two
Programming in Scala - Lecture TwoProgramming in Scala - Lecture Two
Programming in Scala - Lecture Two
 
C# Generics
C# GenericsC# Generics
C# Generics
 
Java q ref 2018
Java q ref 2018Java q ref 2018
Java q ref 2018
 
Demystifying functional programming with Scala
Demystifying functional programming with ScalaDemystifying functional programming with Scala
Demystifying functional programming with Scala
 
Programming in Scala - Lecture One
Programming in Scala - Lecture OneProgramming in Scala - Lecture One
Programming in Scala - Lecture One
 
Programming in Scala - Lecture Three
Programming in Scala - Lecture ThreeProgramming in Scala - Lecture Three
Programming in Scala - Lecture Three
 
Generics in .NET, C++ and Java
Generics in .NET, C++ and JavaGenerics in .NET, C++ and Java
Generics in .NET, C++ and Java
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With Scala
 
Scala Paradigms
Scala ParadigmsScala Paradigms
Scala Paradigms
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming Language
 
Text processing by Rj
Text processing by RjText processing by Rj
Text processing by Rj
 

En vedette

12 Secrets To Raising Capital
12 Secrets To Raising Capital12 Secrets To Raising Capital
12 Secrets To Raising CapitalJose Gonzalez
 
A guide to_private_equity
A guide to_private_equityA guide to_private_equity
A guide to_private_equityJose Gonzalez
 
DotNet &amp; Sql Server Interview Questions
DotNet &amp; Sql Server Interview QuestionsDotNet &amp; Sql Server Interview Questions
DotNet &amp; Sql Server Interview QuestionsNeeraj Kaushik
 
Action trumps-everything
Action trumps-everythingAction trumps-everything
Action trumps-everythingJose Gonzalez
 
Private company secondary markets october 2011
Private company secondary markets   october 2011Private company secondary markets   october 2011
Private company secondary markets october 2011Jason Jones
 
howtodoa120secpitch-091022182522-phpapp02
howtodoa120secpitch-091022182522-phpapp02howtodoa120secpitch-091022182522-phpapp02
howtodoa120secpitch-091022182522-phpapp02Jose Gonzalez
 
Avt secondaries analysis2010
Avt secondaries analysis2010Avt secondaries analysis2010
Avt secondaries analysis2010Jose Gonzalez
 

En vedette (8)

12 Secrets To Raising Capital
12 Secrets To Raising Capital12 Secrets To Raising Capital
12 Secrets To Raising Capital
 
A guide to_private_equity
A guide to_private_equityA guide to_private_equity
A guide to_private_equity
 
DotNet &amp; Sql Server Interview Questions
DotNet &amp; Sql Server Interview QuestionsDotNet &amp; Sql Server Interview Questions
DotNet &amp; Sql Server Interview Questions
 
Action trumps-everything
Action trumps-everythingAction trumps-everything
Action trumps-everything
 
Businessplanguide
BusinessplanguideBusinessplanguide
Businessplanguide
 
Private company secondary markets october 2011
Private company secondary markets   october 2011Private company secondary markets   october 2011
Private company secondary markets october 2011
 
howtodoa120secpitch-091022182522-phpapp02
howtodoa120secpitch-091022182522-phpapp02howtodoa120secpitch-091022182522-phpapp02
howtodoa120secpitch-091022182522-phpapp02
 
Avt secondaries analysis2010
Avt secondaries analysis2010Avt secondaries analysis2010
Avt secondaries analysis2010
 

Similaire à Dot net 3.5 Language Enhancements and LINQ

Similaire à Dot net 3.5 Language Enhancements and LINQ (20)

Understanding linq
Understanding linqUnderstanding linq
Understanding linq
 
Ruby Programming Assignment Help
Ruby Programming Assignment HelpRuby Programming Assignment Help
Ruby Programming Assignment Help
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4th
 
Functional Programming with C#
Functional Programming with C#Functional Programming with C#
Functional Programming with C#
 
Ds lab handouts
Ds lab handoutsDs lab handouts
Ds lab handouts
 
Introduction to c#
Introduction to c#Introduction to c#
Introduction to c#
 
C#2
C#2C#2
C#2
 
Java 8 new features
Java 8 new featuresJava 8 new features
Java 8 new features
 
C# for Java Developers
C# for Java DevelopersC# for Java Developers
C# for Java Developers
 
Java-Intro.pptx
Java-Intro.pptxJava-Intro.pptx
Java-Intro.pptx
 
Java gets a closure
Java gets a closureJava gets a closure
Java gets a closure
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)
 
Python ppt
Python pptPython ppt
Python ppt
 
Java introduction
Java introductionJava introduction
Java introduction
 
2CPP15 - Templates
2CPP15 - Templates2CPP15 - Templates
2CPP15 - Templates
 
Nitin Mishra 0301EC201039 Internship PPT.pptx
Nitin Mishra 0301EC201039 Internship PPT.pptxNitin Mishra 0301EC201039 Internship PPT.pptx
Nitin Mishra 0301EC201039 Internship PPT.pptx
 
Chapter 3 part2
Chapter 3  part2Chapter 3  part2
Chapter 3 part2
 
Functions
FunctionsFunctions
Functions
 
Programming with Python - Week 3
Programming with Python - Week 3Programming with Python - Week 3
Programming with Python - Week 3
 
Lambdas and Laughs
Lambdas and LaughsLambdas and Laughs
Lambdas and Laughs
 

Plus de Neeraj Kaushik

How to place orders through FIX Message
How to place orders through FIX MessageHow to place orders through FIX Message
How to place orders through FIX MessageNeeraj Kaushik
 
Implementation of fix messages for fix 5.0 sp2 and fixt1.1 specification
Implementation of fix messages for fix 5.0 sp2 and fixt1.1 specificationImplementation of fix messages for fix 5.0 sp2 and fixt1.1 specification
Implementation of fix messages for fix 5.0 sp2 and fixt1.1 specificationNeeraj Kaushik
 
C-Sharp Arithmatic Expression Calculator
C-Sharp Arithmatic Expression CalculatorC-Sharp Arithmatic Expression Calculator
C-Sharp Arithmatic Expression CalculatorNeeraj Kaushik
 
Implement Search Screen Using Knockoutjs
Implement Search Screen Using KnockoutjsImplement Search Screen Using Knockoutjs
Implement Search Screen Using KnockoutjsNeeraj Kaushik
 
Multithreading Presentation
Multithreading PresentationMultithreading Presentation
Multithreading PresentationNeeraj Kaushik
 
Concurrent Collections Object In Dot Net 4
Concurrent Collections Object In Dot Net 4Concurrent Collections Object In Dot Net 4
Concurrent Collections Object In Dot Net 4Neeraj Kaushik
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot NetNeeraj Kaushik
 

Plus de Neeraj Kaushik (12)

How to place orders through FIX Message
How to place orders through FIX MessageHow to place orders through FIX Message
How to place orders through FIX Message
 
Futures_Options
Futures_OptionsFutures_Options
Futures_Options
 
No sql
No sqlNo sql
No sql
 
Implementation of fix messages for fix 5.0 sp2 and fixt1.1 specification
Implementation of fix messages for fix 5.0 sp2 and fixt1.1 specificationImplementation of fix messages for fix 5.0 sp2 and fixt1.1 specification
Implementation of fix messages for fix 5.0 sp2 and fixt1.1 specification
 
C-Sharp Arithmatic Expression Calculator
C-Sharp Arithmatic Expression CalculatorC-Sharp Arithmatic Expression Calculator
C-Sharp Arithmatic Expression Calculator
 
Implement Search Screen Using Knockoutjs
Implement Search Screen Using KnockoutjsImplement Search Screen Using Knockoutjs
Implement Search Screen Using Knockoutjs
 
Multithreading Presentation
Multithreading PresentationMultithreading Presentation
Multithreading Presentation
 
Concurrent Collections Object In Dot Net 4
Concurrent Collections Object In Dot Net 4Concurrent Collections Object In Dot Net 4
Concurrent Collections Object In Dot Net 4
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
 
Quick Fix Sample
Quick Fix SampleQuick Fix Sample
Quick Fix Sample
 
Design UML diagrams
Design UML diagramsDesign UML diagrams
Design UML diagrams
 
Design UML diagrams
Design UML diagramsDesign UML diagrams
Design UML diagrams
 

Dot net 3.5 Language Enhancements and LINQ

  • 1. What’s New in Dot net 3.5
  • 2. Automatic Properties • Extension Methods • Object Initialization • Anonymous Types • Partial Methods • Type Inference • LINQ • Lambda Expression • Query Expression • All Together
  • 3. Language Enhancements + Query Expressions = LINQ Language Enhancements consists of – Local Variable Type Inference – Object Initialisers – Anonymous Types – Lambda Expressions – Extension Methods
  • 4. • No need of private variable • When no extra logic is required in get and set • private set is used for making read-only property • prop + double tab is code snippet
  • 5. public class Product { private string name; private decimal price; public string Name { get { return name; } set { name = value; } } public decimal Price { get { return price; } set { price = value; } } }
  • 6. public class Product { Must have both public string Name { get; set; } get and set public decimal Price { get; set; } } public class Product { public string Name { get; private set; } public decimal Price { get; set; } Read only } property
  • 7. Equivalent to calling the static method • Can access only public members. • Can add methods to other classes ◦ any methods (although look static) ◦ only from static classes • When import a namespace that has extensions, then added to classes ◦ once imported, called as usual • Local methods take precedence ◦ first local for normal method, then extension
  • 8. namespace MyStuff Extension { method public static class Extensions { public static string Concatenate(this IEnumerable<string> strings, string separator) {…} } } Brings extensions into using MyStuff; scope obj.Foo(x, y)  string[] names = new string[] { "Axel", "Mia", "Niels" }; XXX.Foo(obj, x, y) string s = names.Concatenate(", "); IntelliSense!
  • 9. Can initialize fields like attribute fields ◦ new C(1, 2, name=“my class”); ◦ works if public field or if property with set ◦ can be nested (eg. Rectangle with two Points) • Collection initializers ◦ List<int> digits = new List<int> { 0, 1}; ◦ Must implement System.Generic.ICollection<T> • Object initializers ◦ var a = new Point { X = 0, Y = 1 };
  • 10. 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;
  • 11. Must implement Must have public IEnumerable Add method List<int> numbers = new List<int> { 1, 10, 100 }; List<int> numbers = new List<int>(); Add can take numbers.Add(1); more than one numbers.Add(10); parameter numbers.Add(100); Dictionary<int, string> spellings = new Dictionary<int, string> { { 0, "Zero" }, { 1, "One" }, { 2, "Two" }, { 3, "Three" } };
  • 12. Type of the variable induced from expression ◦ must include initializer ◦ can’t be null. Why not?  What happens if “var” is a class in scope?  Works in foreach loops
  • 13. var can only be used when a local variable is declared and initialized in the same statement; the variable cannot be initialized to null literal, because it does not have a type – like lambda expressions or method groups. However, it can be initialized with an expression that happens to have the value null, as long as the expression has a type. • var cannot be used on fields in class scope. • Variables declared by using var cannot be used in their own initialization expression. In other words, var v = v++; will result in a compile-time error. • Multiple implicitly-typed variables cannot be initialized in the same statement. • If a type named var is in scope, then we will get a compile-time error if we attempt to initialize a local variable with the var keyword.
  • 14. 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>(); “The type on the right hand side”
  • 15. var x = new {p1 = 10, p2 = “name”}; ◦ x is of anonymous type ◦ type can’t be referred to by name in program • structural type equivalence ◦ two anonymous types can be compatible • implicitly typed arrays ◦ var a = new[] { 1, 10, 100, 1000 }; ◦ must have consistent types ◦ or have implicit conversions
  • 16. IEnumerable<Contact> phoneListQuery = from c in customers where c.State == "WA" select new Contact { Name = c.Name, Phone = c.Phone }; + public class Contact { public string Name; public string Phone; }
  • 17. IEnumerable< Contact > class Contact { public string Name; public string Phone; var phoneListQuery = } from c in customers where c.State == "WA" select new { Name = c.Name, Phone = c.Phone }; Contact foreach (var entry in phoneListQuery) { Console.WriteLine(entry.Name); Console.WriteLine(entry.Phone); }
  • 18. Partial methods are methods living in partial classes which are marked as partial • The method must return void. • No access modifiers or attributes are allowed. Partial methods are implicitly private. • Partial methods method hooks, similar to event handlers, that developers may decide to implement or not. • If the developer does not supply an implementation, the compiler removes the signature at compile time.
  • 19. partial class A { partial void OnSomethingHappened(string s); } // This part can be in a separate file. partial class A { // Comment out this method and the program // will still compile. partial void OnSomethingHappened(String s) { Console.WriteLine("Something happened: {0}", s); } }
  • 20. Unified programming model for any data type/source • Collections • Database Relational Data • XML Files • Extendable for anything else • Introduce more declarative syntax • Data is equivalent to Objects
  • 21. C# 3.0 VB 9.0 Others… .NET Language-Integrated Query (LINQ) LINQ enabled ADO.NET LINQ LINQ LINQ LINQ LINQ To to To To to Objects Entities SQL Dataset XML Objects Relational Data XML
  • 22. Syntax based on Extension methods • Some Extension methods may be replaced by language keywords – where, orderby, select, group, … • Auxiliary language features in use – Automatic properties – Anonymous types – Implicitly typed local variables – Object initializers
  • 23. Working with collections ◦ Any one that implements IEnumerable<T> • using System.Linq
  • 24. Generalized function syntax ◦ x.x+1 ◦ in C# 3.0, have x => x + 1 • From anonymous delegate syntax: ◦ delegate(int x) { return x + 1;} • Can have implicitly typed variables • Can have more than one variable • Can have expression or statement body
  • 25. Can be converted to delegate type ◦ if parameters and body match ◦ delegate R Func<A,R>(A arg); Func<int,int> f1 = x => x + 1; Func<int,double> f2 = x => x + 1; Func<double,int> f3 = x => x + 1; • Participate in type inference • If expression body, get expression trees
  • 26. public delegate bool Predicate<T>(T obj); public class List<T> { public List<T> FindAll(Predicate<T> test) { List<T> result = new List<T>(); foreach (T item in this) if (test(item)) result.Add(item); return result; } … }
  • 27. public class MyClass { public static void Main() { List<Customer> customers = GetCustomerList(); List<Customer> locals = customers.FindAll( new Predicate<Customer>(StateEqualsWA) ); } static bool StateEqualsWA(Customer c) { return c.State == "WA"; } }
  • 28. public class MyClass { public static void Main() { List<Customer> customers = GetCustomerList(); List<Customer> locals = customers.FindAll( delegate(Customer c) { return c.State == "WA"; } ); } }
  • 29. public class MyClass { public static void Main() { List<Customer> customers = GetCustomerList(); List<Customer> locals = customers.FindAll(c => c.State == "WA"); } } Lambda expression
  • 30. Adds querying to language ◦ important for interaction with DB ◦ but also with built-in data structures ◦ leave query planning to data structure designer • Implemented using above functionality ◦ anonymous types and variables useful ◦ lambda expressions make it cleaner.
  • 31. Starts with from Zero or more from, join, let, wher from id in source e, or orderby { from id in source | join id in source on expr equals expr [ into id ] | let id = expr | where condition | Ends with select or group by orderby ordering, ordering, … } select expr | group expr by key [ into id query ] Optional into continuation
  • 32. Queries translate to method invocations ◦ Where, Join, OrderBy, Select, 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 });
  • 33. Project Select <expr> Filter Where <expr>, Distinct Test Any(<expr>), All(<expr>) Join <expr> Join <expr> On <expr> Equals <expr> Group Group By <expr>, <expr> Into <expr>, <expr> Group Join <decl> On <expr> Equals <expr> Into <expr> Aggregate Count(<expr>), Sum(<expr>), Min(<expr>), Max(<expr>), Avg(<expr>) Partition Skip [ While ] <expr>, Take [ While ] <expr> Set Union, Intersect, Except Order Order By <expr>, <expr> [ Ascending | Descending ]
  • 34. var contacts = Query expressions from c in customers where c.State == "WA" select new { c.Name, c.Phone }; type inference Lambda expressions var contacts = customers .Where(c => c.State == "WA") .Select(c => new { c.Name, c.Phone }); Extension methods Anonymous Object types initializers