C#3.0 & Vb 9.0 New Features

Post on 10-May-2015

2.074 views 9 download

Tags:

Transcript of C#3.0 & Vb 9.0 New Features

C# 3.0 and VB 9.0 New Featuresof VS2008

C# and VB Feature List

C# 3.0 VB 9.0

Extension MethodsLambda ExpressionsLINQExpression Trees

Extension MethodsLambda ExpressionsLINQ and Embedded XML Expression Trees

Extension Methods

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

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

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

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

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

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

Guidelines for Extension Method

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

Use sparingly only when you have to

Useful Extension Methods

http://www.extensionmethod.net/

Lambda Expressions

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

and obtaining a delegate to function we write.

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

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)

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)

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

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

Lambda Expressions - Uses

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

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

LINQ

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

A LINQ Query

C#

VB

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

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

Typed Results using LINQ

LINQ and Anonymous Types

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

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

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

Evolution of LINQ

Comparison of LINQ and SQL Query

Projection

Filtering

Filtering

Sub Query

Joins

Cross Join

Inner Join

Joins

Outer Join

Set Operators

Set Operators

Aggregate Operations

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

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

and submit changes back LINQ to SQL ORM

Deferred Execution

Immediate Execution

DLINQ

XLINQQuery expressions against XML

XLINQ API

XAttribute XNode

XCharacterNode

XCData

XComment XContainer XDeclaration

XDocument

XDocumentType

XElement

XName

XProcessingInstruction

XText(internal)

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

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.

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

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

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

Embedded XML

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.

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.

Embedded XML in VB

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

Expression Trees

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

Expression Tree Graph

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

Building Expression trees

Creating an expression

Initialize the Members

Building Expression trees

Form an expression

Execute an expression

Expression Tree Visualizer

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)

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