64
C# 3.0 and VB 9.0 New Features of VS2008

C#3.0 & Vb 9.0 New Features

Embed Size (px)

Citation preview

Page 1: C#3.0 & Vb 9.0 New Features

C# 3.0 and VB 9.0 New Featuresof VS2008

Page 2: C#3.0 & Vb 9.0 New Features

C# and VB Feature List

C# 3.0 VB 9.0

Extension MethodsLambda ExpressionsLINQExpression Trees

Extension MethodsLambda ExpressionsLINQ and Embedded XML Expression Trees

Page 3: C#3.0 & Vb 9.0 New Features

Extension Methods

Page 4: C#3.0 & Vb 9.0 New Features

Extension Methods in C# Allows to extend existing types and constructed types with

additional methods, without having to sub-class it or recompile the original type

Static methods that can be invoked using instance method syntax

Page 5: C#3.0 & Vb 9.0 New Features

Extension Methods in C# Applied not just to individual types, but also to parent base

class or interface within DOTNET framework If “this” keyword precedes an “object”, then it indicates that

the extension method should be applied to all types that derive from the base System.Object base type. The method can be applied on every object in .NET

Powerful way to inject our own custom functionality into existing types

Functionally same as wrapper classes; only difference is Design time syntax

Extension method with same name as Class/Interface method will never be called.

Have lower priority than instance methods defined in type

Page 6: C#3.0 & Vb 9.0 New Features

Extension Methods in C# To add a new method to existing type, Create a static

method in a static class and import the namespace in the class in which it is needed

Page 7: C#3.0 & Vb 9.0 New Features

Extension Methods in VB Decorated with “Extension” attribute (in System.Runtime.CompilerServices) Preferred over Shared utility methods Should be in a Module

Page 8: C#3.0 & Vb 9.0 New Features

Pros of Extension Methods

Can be called on Null objectsComposability – Chaining of operationsLINQAdd functionality without altering existing code.NET types, third party types, older COM/Active X

types can be extendedProvide concrete implementation to interfaces

Page 9: C#3.0 & Vb 9.0 New Features

Cons of Extension MethodsNot a replacement to InheritanceCode Hijack / SecurityAdding a Real method to an object with same name

as extension method gives precedence for Real method

Properties cannot be extendedSimilar to Wrapper classes, only access public

methods and cannot read/write protected membersCounter-Intuitive – Specified in the order opposite to

the order of execution

Page 10: C#3.0 & Vb 9.0 New Features

Guidelines for Extension Method

Can be used to extend a class/interface but not to override them

Use sparingly only when you have to

Page 11: C#3.0 & Vb 9.0 New Features

Useful Extension Methods

http://www.extensionmethod.net/

Page 12: C#3.0 & Vb 9.0 New Features

Lambda Expressions

Page 13: C#3.0 & Vb 9.0 New Features

Lambda Expressions in C# 3.0 Compact way of writing functions in middle of expressions

and obtaining a delegate to function we write.

Page 14: C#3.0 & Vb 9.0 New Features

Lambda Expressions

A lambda expression is written as a parameter list

followed by => token and then followed by

an expression or statement block to be executed when statement is invoked.

Params=> expression

Page 15: C#3.0 & Vb 9.0 New Features

Lambda Expression• Add (a, b) => (a + b)• AddChecked (a, b) => (a + b)• And (a, b) => (a And b)• AndAlso (a, b) => (a && b)• ArrayIndex (a, i) => a[i]• ArrayLength a => ArrayLength(a)• Call a => Abs(a)• Coalesce s => (s ?? "(null)")• Conditional (b, t, f) => IIF(b, t, f)• Constant () => 123• Convert a => Convert(a)• ConvertChecked a => ConvertChecked(a)• Divide (a, b) => (a / b)• Equal (a, b) => (a = b)• ExclusiveOr (a, b) => (a ^ b)• GreaterThan (a, b) => (a > b)

Page 16: C#3.0 & Vb 9.0 New Features

Lambda Expression

• GreaterThanOrEqual (a, b) => (a >= b)• Invoke a => Invoke(a)• Lambda a => a• LeftShift (a, s) => (a << s)• LessThan (a, b) => (a < b)• LessThanOrEqual (a, b) => (a <= b)• ListInit () => new List`1() {Void Add(Int32)(1)}• MemberAccess m => m.i• MemberInit a => new MemberAccess() {i = a}• Modulo (a, b) => (a % b)• Multiply (a, b) => (a * b)• MultiplyChecked (a, b) => (a * b)• Negate a => -a• NegateChecked a => -a• New n => new String(a, n)

Page 17: C#3.0 & Vb 9.0 New Features

Lambda Expression• NewArrayBounds n => new System.Int32[*](n)• NewArrayInit () => new [] {}• Not b => Not(b)• NotEqual (a, b) => (a != b)• Or (a, b) => (a Or b)• OrElse (a, b) => (a || b)• Parameter a => a• Power (a, e) => (a ^ e)• Quote () => 1• RightShift (a, s) => (a >> s)• Subtract (a, b) => (a - b)• SubtractChecked (a, b) => (a - b)• TypeAs o => (o As String)• TypeIs o => (o Is String)• UnaryPlus a => +a

Page 18: C#3.0 & Vb 9.0 New Features

Lambda Expression - Features

First class citizens Can be returned from a function Can be passed to a function Can be used as Callback delegates Return statement in lambda expression does not return an

enclosing method Cannot contain goto statement/ break statement/ continue

statement whose target is outside the body or in the body of contained anonymous function

Page 19: C#3.0 & Vb 9.0 New Features

Lambda Expressions - Uses

Used In LINQ Query expressions Used in Construction of Expression trees Used in place of Delegates

Page 20: C#3.0 & Vb 9.0 New Features

Lambda Expressions - Cons

Can include only expressions and not statements Single Expressions in VB 9.0 Variable captured will not be garbage collected unless the

delegate that references it goes out of scope Variables inside lambda expression are not visible outside the

method Cannot capture ref or out parameter from an enclosing

method Recursive Lambda expressions cannot be written

Page 21: C#3.0 & Vb 9.0 New Features

LINQ

Page 22: C#3.0 & Vb 9.0 New Features

Language Integrated Query (LINQ)

Express efficient query behavior in programming language, transforms the query results into any format, and easily manipulate the results.

Full type safety and compile time checking of query expressions

LINQ query returns objects of type IEnumerable

Page 23: C#3.0 & Vb 9.0 New Features

A LINQ Query

C#

VB

Page 24: C#3.0 & Vb 9.0 New Features

LINQ Operators

• Restriction - Where• Projection - Select, SelectMany• Partitioning - Take, Skip, TakeWhile, SkipWhile• Ordering - OrderBy, OrderByDescending, ThenBy,

ThenByDecending, Reverse• Grouping - GroupBy• Set - Distinct, Union, Intersect, Except• Conversion – ToArray, ToDictionary, ToList, OfType

Page 25: C#3.0 & Vb 9.0 New Features

LINQ Operators

• Element – First, FirstOrDefault, ElementAt• Generation – Range,Repeat• Quantifiers – Any, All• Aggregate - Count, Sum, Min, Max, Average, Fold• Miscellaneous - Concat, EqualAll• Custom Sequence - Combine• Query Execution - Deferred, Immediate, Query Reuse

Page 26: C#3.0 & Vb 9.0 New Features

Typed Results using LINQ

Page 27: C#3.0 & Vb 9.0 New Features

LINQ and Anonymous Types

Page 28: C#3.0 & Vb 9.0 New Features

Pros of Type inference Make Code Simpler

Used for creating Anonymous types Iterate over IEnumerable<T> results where T is a projected

anonymous type Used in LINQ expressions

Page 29: C#3.0 & Vb 9.0 New Features

LINQ with Lambda Expressions Anonymous methods required parameter type to be

explicitly stated.

Lambda expressions permit parameter types to be omitted and allow them to be inferred based on usage.

Explicit type declaration is also allowed

Anonymous Methods

Page 30: C#3.0 & Vb 9.0 New Features

Lambda Expressions in VB

Lambda expression is an Inline function that you can pass to something that takes the delegate

Func type – Allows 4 arguments as leading generic parameters and 1 last generic parameter as return type

Page 31: C#3.0 & Vb 9.0 New Features

Evolution of LINQ

Page 32: C#3.0 & Vb 9.0 New Features

Comparison of LINQ and SQL Query

Page 33: C#3.0 & Vb 9.0 New Features

Projection

Page 34: C#3.0 & Vb 9.0 New Features

Filtering

Page 35: C#3.0 & Vb 9.0 New Features

Filtering

Page 36: C#3.0 & Vb 9.0 New Features

Sub Query

Page 37: C#3.0 & Vb 9.0 New Features

Joins

Cross Join

Inner Join

Page 38: C#3.0 & Vb 9.0 New Features

Joins

Outer Join

Page 39: C#3.0 & Vb 9.0 New Features

Set Operators

Page 40: C#3.0 & Vb 9.0 New Features

Set Operators

Page 41: C#3.0 & Vb 9.0 New Features

Aggregate Operations

Page 42: C#3.0 & Vb 9.0 New Features

LINQ Query Samples

101 LINQ C# Samples http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx

101 LINQ VB Samples http://msdn.microsoft.com/en-us/vbasic/bb688088.aspx

Page 43: C#3.0 & Vb 9.0 New Features

DLINQ Query expressions against Relational data Data Context is the conduit to retrieve data from database

and submit changes back LINQ to SQL ORM

Page 44: C#3.0 & Vb 9.0 New Features

Deferred Execution

Immediate Execution

DLINQ

Page 45: C#3.0 & Vb 9.0 New Features

XLINQQuery expressions against XML

Page 46: C#3.0 & Vb 9.0 New Features

XLINQ API

XAttribute XNode

XCharacterNode

XCData

XComment XContainer XDeclaration

XDocument

XDocumentType

XElement

XName

XProcessingInstruction

XText(internal)

Page 47: C#3.0 & Vb 9.0 New Features

Pros of LINQ• Avoids dynamic creation of queries hardcoded as strings

inside Code • Full type safety • Gives more power to manipulate data. Big advantage

over datasets. • Extensibility and expression trees allow mostly

consistent querying of multiple sources • Common syntax for querying any data source -

Relational, XML or In memory datasets or .NET objects• Can be used against .NET 1.0 or .NET 2.0 objects • Able to Extend LINQ to support new classes and

technologies

Page 48: C#3.0 & Vb 9.0 New Features

Pros – LINQ (Continued) Ability to access Stored procedures and user defined

functions in Database Integrated to .NET framework and Accessible from any .NET

compliant language Data manipulation logic/code is written in the application Declarative approach makes queries easier to understand and

more compact Even in-process queries can be implemented in ways other

than LINQ to Objects - e.g. Parallel LINQ and my own Push LINQ framework. Very flexible.

Page 49: C#3.0 & Vb 9.0 New Features

Pros – LINQ (Continued) Fabulously useful for in-process queries, where it's easiest to

understand Wide range of operators provided by default, and others can

easily be added for LINQ to Objects Language features introduced primarily for LINQ are widely

applicable elsewhere Consistent Domain Modeling Hiding the mundane code Short learning curve Intelli-sense and Designer support in Visual Studio

Page 50: C#3.0 & Vb 9.0 New Features

Cons of LINQ Query expressions aren't understood well enough, and are

overused. Often simple method invocation is shorter and simpler.

Inevitable inconsistencies between provider - impedance mismatch is still present, which is reasonable but needs to be understood

There will always be some things you can do in SQL but not in LINQ

Without understanding what's going on, it's easy to write very inefficient code

It's hard to write a LINQ provider. It's a new way of thinking about data access for most

developers, and will need time for understanding to percolate

Page 51: C#3.0 & Vb 9.0 New Features

Cons of LINQ (Continued) Some operators are "missing", particularly the equivalents of

OrderBy for things other than ordering - e.g. finding the item with the maximum value of a property

Deferred execution and streaming are poorly understood (but improving)

Debugging can be very tricky due to deferred execution and streaming

Data manipulation logic/code is written in the application. Cannot change logic without recompiling (Unlike Stored procedures)

Problem of viewing Execution plan and optimizing query

Page 52: C#3.0 & Vb 9.0 New Features

Embedded XML

Page 53: C#3.0 & Vb 9.0 New Features

Embedded XML in VB VB 9.0 provides deep support for XLINQ through XML literals

and late binding over XML. XML Literals allow straight XML to be embedded into the

source code. XML has become the first class citizen in Vb.NET.

Page 54: C#3.0 & Vb 9.0 New Features

Embedded XML in VBThe XML API helps us constructing the XML as follows

The compiler knows to use late binding over XML when the target expression is of type, or collection of, XElement, XDocument, or XAttribute.

Page 55: C#3.0 & Vb 9.0 New Features

Embedded XML in VB

The XML Support together with LINQ makes it possible to dynamically query and generate an XML.

Page 56: C#3.0 & Vb 9.0 New Features

Expression Trees

Page 57: C#3.0 & Vb 9.0 New Features

What are Expression Trees

A form of Data structure Represent Language level code in form of data Data is stored in Tree shaped structure Exposes parts of an expression by delineating code into data Each node in tree is an expression

Page 58: C#3.0 & Vb 9.0 New Features

Expression Tree Graph

Page 59: C#3.0 & Vb 9.0 New Features

Expression Trees

Higher level representation of query expressions which permit lambda expressions to be represented as data (expression trees) instead of as code (delegates).

C#

VB

Page 60: C#3.0 & Vb 9.0 New Features

Building Expression trees

Creating an expression

Initialize the Members

Page 61: C#3.0 & Vb 9.0 New Features

Building Expression trees

Form an expression

Execute an expression

Page 62: C#3.0 & Vb 9.0 New Features

Expression Tree Visualizer

Page 63: C#3.0 & Vb 9.0 New Features

Uses of Expression Trees• Play main role in LINQ to SQL• LINQ to SQL queries returns objects of type IQueryable<T>

• LINQ to SQL queries are not executed in C# program; Translated to SQL, sent across wire and executed in Database server

• Code found in a query expression has to be translated into a SQL query

• Easier to translate a data structure into SQL than executable code• Queries that return IEnumerable<T> do not use expression trees

(LINQ to Objects)

Page 64: C#3.0 & Vb 9.0 New Features

C# 4.0 and VB 10.0 (VS2010)

C# 4.0 VB 10.0

Dynamic lookupOptional and Named ParametersGeneric Co variance and Contra varianceImproved COM interoperabilityNo PIAParallel Programming, PLINQ

Dynamic Type

Generic Co variance and Contra varianceImproved COM interoperabilityNo PIAParallel Programming, PLINQAnonymous DelegatesImplicit Line continuationAuto Implemented PropertiesCollection InitialisersArray literalsNullable Optional Parameters