whats new in c# 4 0 - netponto

Post on 06-May-2015

2.849 Views

Category:

Technology

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

What's New In C# 4.0

• The Evolution Of C#• Covariance And Contravariance• Named And Optional Arguments• Dynamic Programming• COM Interop Improvements

Agenda

The Evolution Of C#

C# 1.0Managed

C# 2.0Generics

C# 3.0LINQ

The Evolution Of C#

Trends

Declarative

ConcurrentDynamic

Dynamic vs. Static

DynamicLanguagesSimple and

succinctImplicitly typed

Meta-programming

No compilation

StaticLanguages

Robust

Performant

Intelligent tools

Better scaling

VB

C#C# VB

Co-Evolution

• Named Arguments

• Optional Arguments

• Index Properties (COM)

• Lambda Statements

• Auto-Implemented Properties

• Colection Initializers

C# 1.0Managed

C# 2.0Generics

C# 3.0LINQ

C# 4.0Dynamic Programming

The Evolution Of C#

• The Evolution Of C#• http://paulomorgado.net/en/blog/archive/2010/04/1

2/the-evolution-of-c.aspx

Resources

Covariance And Contravariance

In multilinear algebra and tensor analysis, covariance and contravariance describe how the quantitative description of certain geometrical or physical entities changes when passing from one coordinate system to another.

Wikipedia

Covariance And Contravarance

Type T is greater than (>) type S if S is a subtype of (derives from) T

Covariance And Contravarance

T ≥ Stypeof(T).IsAssignableFrom(typeof(S))

• Give 2 types Base and Derived, such that:• There is a reference (or identity) conversion between Base and

Derived• Base ≥ Derived

• A generic type definition Generic<T> is:• Covariant in T

• If Genérico<Base> ≥ Genérico<Derived>

• Contravariant in T• If Genérico<Base> ≤ Genérico<Derived>

• Invariant in T• If neither of the above apply

Covariance And Contravarance

Contravariante em Ttypeof(Base).IsAssignableFrom(typeof(Derived))

typeof(G<Derived>).IsAssignableFrom(typeof(G<Base>))

Covariante em Ttypeof(Base).IsAssignableFrom(typeof(Derived))

typeof(G<Base>).IsAssignableFrom(typeof(G<Derived>))

Covariance And Contravarance

Covariance And Contravarance

string[] strings = GetStringArray();Process(strings);

void Process(object[] objects){ objects[0] = "Hello"; // Ok objects[1] = new Button(); // Exception!}

C# (.NET) arrays are covariant

… but not safely

covariant

void Process(object[] objects) { … }

Covariance And Contravarance

List<string> strings = GetStringList();Process(strings);

Until now, C# (.NET) generics

have been invariant

void Process(IEnumerable<object> objects){ // IEnumerable<T> is read-only and // therefore safely covariant}

C# 4.0 supports safe covariance and contravariance

void Process(IEnumerable<object> objects) { … }

Safe Covariance

public interface IEnumerable<T>{ IEnumerator<T> GetEnumerator();}

public interface IEnumerator<T>{ T Current { get; } bool MoveNext();}

public interface IEnumerable<out T>{ IEnumerator<T> GetEnumerator();}public interface IEnumerator<out T>{ T Current { get; } bool MoveNext();}

out = covariantOutput positions only

IEnumerable<string> strings = GetStrings();IEnumerable<object> objects = strings;

Can be treated as less derived

Safe Contravariance

public interface IComparer<T>{ int Compare(T x, T y);}

public interface IComparer<in T>{ int Compare(T x, T y);} IComparer<object> objComp =

GetComparer();IComparer<string> strComp = objComp;

in = contravariantInput positions only

Can be treated as more derived

• Supported for generic interface and delegate types only.

• Verified/enforced staticaliy in the definition.• Value types are always invariant• IEnumerable<int> is not IEnumerable<object>• Similar to existing rules for arrays

• ref and out parameters need invariant types

Variance In C# 4.o

Interfaces

• System.Collections.Generic.IEnumerable<out T>• System.Collections.Generic.IEnumerator<out T>• System.Linq.IQueryable<out T>• System.Collections.Generic.IComparer<in T>• System.Collections.Generic.IEqualityComparer<in T>• System.IComparable<in T>

Delegates

• System.Func<in T, …, out R>• System.Action<in T, …>• System.Predicate<in T>• System.Comparison<in T>• System.EventHandler<in T>

Variance In .NET 4.0

• Covariance And Contravariance In Generics• http://paulomorgado.net/en/blog/archive/2010/04/13/c-4-0-covariance-and-contrav

ariance-in-generics.aspx

• Covariance And Contravariance In Generics Made Easy• http://paulomorgado.net/en/blog/archive/2010/04/15/c-4-0-covariance-and-contravaria

nce-in-generics-made-easy.aspx

• Covarince and Contravariance in Generics• http://msdn.microsoft.com/library/dd799517(VS.100).aspx

• Exact rules for variance validity• http://blogs.msdn.com/ericlippert/archive/2009/12/03/exact-rules-for-variância-validity.aspx

• Events get a little overhaul in C# 4, Afterward: Effective Events• http://

blogs.msdn.com/cburrows/archive/2010/03/30/events-get-a-little-overhaul-in-c-4-afterward-effective-events.aspx

Resources

Named And Optional Arguments

Named And Optional Arguments

Greeting("Mr.", "Morgado", 42);

public void Greeting(string title, string name, int age)

Arguments

Parameters

They always have names

They are never

optional

Named Arguments

int i = 0;Method(i, third: i++, second: ++i);

public void Method(int first, int second, int third)

int i = 0;int CS$0$0000 = i++;int CS$0$0001 = ++i;Method(i, CS$0$0001, CS$0$0000);

Optional Arguments

int i = 0;Method(i, third: ++i);

public void Method(int first, int second = 2, int third = 3) public void Method(int first, int second = 5, int third = 6)

public void Method(int first)

int i = 0;int CS$0$0000 = ++i;Method(i, 2, CS$0$0000);

public void Method(int first, int second) They look like overloads.

But they

aren’t!

• Argument Classes

Optional Arguments - Alternative

XmlReaderSettings settings = new XmlReaderSettings();settings.ValidationType = ValidationType.Auto;XmlReader.Create("file.xml", settings);

XmlReader.Create( "file.xml", new XmlReaderSettings { ValidationType = ValidationType.Auto });

XmlReader.Create( "file.xml", new { ValidationType = ValidationType.Auto }); Not y

et!

• C# 4.0: Named And Optional Arguments• http://paulomorgado.net/en/blog/archive/2010/04/16/c-4-0-named-and-opti

onal-arguments.aspx

• C# 4.0: Alternative To Optional Arguments• http://paulomorgado.net/en/blog/archive/2010/04/18/c-4-0-alternative-to-o

ptional-arguments.aspx

• Named and Optional Arguments (C# Programming Guide)• http://msdn.microsoft.com/library/dd264739(VS.100).aspx

Resources

Dynamic Programming

Dynamic Language Runtime

PythonBinder

RubyBinder

COMBinder

JavaScript

Binder

ObjectBinder

Dynamic Language RuntimeExpression Trees

Dynamic Dispatch

Call Site Caching

IronPython

IronRuby C# VB.NET Others…

Objectos Tipados Dinâmicamente

Calculator calculator = GetCalculator();int sum = calc.Add(10, 20);object calculator = GetCalculator();

Type calculatorType = calculator.GetType();object res = calculatorType.InvokeMember("Add", BindingFlags.InvokeMethod, null, calculator, new object[] { 10, 20 });int sum = Convert.ToInt32(res);

ScriptObject calculator = GetCalculator();object res = calculator.Invoke("Add", 10, 20);int sum = Convert.ToInt32(res);

dynamic calc = GetCalculator();int sum = calc.Add(10, 20);

Statically typed to be dynamic

Dynamic method

invocation

Dynamic conversion

Dynamically Typed Objects

dynamic x = 1;dynamic y = "Hello";dynamic z = new List<int> { 1, 2, 3 };

Compile-time type

dynamic

Run-time typeSystem.Int32

When operand(s) are dynamic:• Member selection deferred to run-time• At run-time, actual type(s) substituted for dynamic• Static result type of operation is dynamic

Dynamically Typed Objectspublic static class Math{ public static decimal Abs(decimal value); public static double Abs(double value); public static float Abs(float value); public static int Abs(int value); public static long Abs(long value); public static sbyte Abs(sbyte value); public static short Abs(short value); ...}

double x = 1.75;double y = Math.Abs(x);

dynamic x = 1.75;dynamic y = Math.Abs(x);

Method chosen at compile-time:

double Abs(double x)

Method chosen atrun-time:double

Abs(double x)

dynamic x = 2;dynamic y = Math.Abs(x);

Method chosen atrun-time:

int Abs(int x)

• IDynamicMetaObjectProvider• Represents a dynamic object that can have operations

determined at run-time.

• DynamicObject : IDynamicMetaObjectProvider• Enables you to define which operations can be performed

on dynamic objects and how to perform those operations.

• ExpandoObject : IDynamicMetaObjectProvider• Enables you to add and delete members of its instances

at run time and also to set and get values of these members.

Building Dynamic Objects

• Dynamic Programming• http://paulomorgado.net/en/blog/archive/2010/04/18/c-4-0-dynamic-progra

mming.aspx

• C# Proposal: Compile Time Static Checking Of Dynamic Objects• http://paulomorgado.net/en/blog/archive/2010/03/19/c-proposal-compile-ti

me-static-checking-of-dynamic-objects.aspx

• Using Type dynamic (C# Programming Guide)• http://msdn.microsoft.com/library/dd264736(VS.100).aspx

• Dynamic Language Runtime Overview• http://msdn.microsoft.com/library/dd233052(v=VS.100).aspx

Resources

COM Interop Improvements

• Named and optional arguments• Ommiting ref• Dynamic Import• Automatic mapping object → dynamic• Indexed properties

• Type Equivalence And Type Embedding (“NO PIA”)

COM Interop Improvements

Ommiting ref

object fileName = "Test.docx";object missing = Missing.Value;

document.SaveAs(ref fileName, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);

document.SaveAs("Test.docx", Missing.Value,  Missing.Value, Missing.Value, Missing.Value,  Missing.Value, Missing.Value, Missing.Value,  Missing.Value, Missing.Value, Missing.Value,  Missing.Value, Missing.Value, Missing.Value,  Missing.Value, Missing.Value);

document.SaveAs("Test.docx");

Dynamic Import

((Excel.Range)(excel.Cells[1, 1])).Value2 = "Hello World!";

excel.Cells[1, 1] = "Hello World!";

Excel.Range range = (Excel.Range)(excel.Cells[1, 1]);

Excel.Range range = excel.Cells[1, 1];

Type Equivalence And Type Embedding (NO PIA)

• COM Interop Improvements• http://paulomorgado.net/en/blog/archive/2010

/04/19/c-4-0-com-interop-improvements.aspx

• Type Equivalence and Embedded Interop Types• http://msdn.microsoft.com/library/dd997297.a

spx

Resources

Demos

Q & A

Conclusion

• The Evolution Of C#• Covariance And Contravariance• Named And Optional Arguments• Dynamic Programming• COM Interop Improvements

Conclusion

• Visual C# Developer Center• http://csharp.net/

• Visual C# 2010 Samples• http://code.msdn.microsoft.com/cs2010samples

• C# Language Specification 4.0• http://www.microsoft.com/downloads/details.aspx?familyid=

DFBF523C-F98C-4804-AFBD-459E846B268E&displaylang=en

Resources

• .NET Reflector• http://www.red-gate.com/products/reflector/

• LINQPad• http://linqpad.net/

• Paulo Morgado• http://PauloMorgado.NET/

Resources

Thank You!

top related