48
What's New In C# 4.0

Whats New In C# 4 0 - NetPonto

Embed Size (px)

Citation preview

Page 1: Whats New In C# 4 0 - NetPonto

What's New In C# 4.0

Page 3: Whats New In C# 4 0 - NetPonto

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

Agenda

Page 4: Whats New In C# 4 0 - NetPonto

The Evolution Of C#

Page 5: Whats New In C# 4 0 - NetPonto

C# 1.0Managed

C# 2.0Generics

C# 3.0LINQ

The Evolution Of C#

Page 6: Whats New In C# 4 0 - NetPonto

Trends

Declarative

ConcurrentDynamic

Page 7: Whats New In C# 4 0 - NetPonto

Dynamic vs. Static

DynamicLanguagesSimple and

succinctImplicitly typed

Meta-programming

No compilation

StaticLanguages

Robust

Performant

Intelligent tools

Better scaling

Page 8: Whats New In C# 4 0 - NetPonto

VB

C#C# VB

Co-Evolution

• Named Arguments

• Optional Arguments

• Index Properties (COM)

• Lambda Statements

• Auto-Implemented Properties

• Colection Initializers

Page 9: Whats New In C# 4 0 - NetPonto

C# 1.0Managed

C# 2.0Generics

C# 3.0LINQ

C# 4.0Dynamic Programming

The Evolution Of C#

Page 10: Whats New In C# 4 0 - NetPonto

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

2/the-evolution-of-c.aspx

Resources

Page 11: Whats New In C# 4 0 - NetPonto

Covariance And Contravariance

Page 12: Whats New In C# 4 0 - NetPonto

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

Page 13: Whats New In C# 4 0 - NetPonto

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))

Page 14: Whats New In C# 4 0 - NetPonto

• 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

Page 15: Whats New In C# 4 0 - NetPonto

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

Page 16: Whats New In C# 4 0 - NetPonto

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) { … }

Page 17: Whats New In C# 4 0 - NetPonto

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) { … }

Page 18: Whats New In C# 4 0 - NetPonto

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

Page 19: Whats New In C# 4 0 - NetPonto

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

Page 20: Whats New In C# 4 0 - NetPonto

• 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

Page 21: Whats New In C# 4 0 - NetPonto

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

Page 22: Whats New In C# 4 0 - NetPonto

• 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

Page 23: Whats New In C# 4 0 - NetPonto

Named And Optional Arguments

Page 24: Whats New In C# 4 0 - NetPonto

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

Page 25: Whats New In C# 4 0 - NetPonto

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);

Page 26: Whats New In C# 4 0 - NetPonto

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!

Page 27: Whats New In C# 4 0 - NetPonto

• 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!

Page 28: Whats New In C# 4 0 - NetPonto

• 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

Page 29: Whats New In C# 4 0 - NetPonto

Dynamic Programming

Page 30: Whats New In C# 4 0 - NetPonto

Dynamic Language Runtime

PythonBinder

RubyBinder

COMBinder

JavaScript

Binder

ObjectBinder

Dynamic Language RuntimeExpression Trees

Dynamic Dispatch

Call Site Caching

IronPython

IronRuby C# VB.NET Others…

Page 31: Whats New In C# 4 0 - NetPonto

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

Page 32: Whats New In C# 4 0 - NetPonto

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

Page 33: Whats New In C# 4 0 - NetPonto

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)

Page 34: Whats New In C# 4 0 - NetPonto

• 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

Page 35: Whats New In C# 4 0 - NetPonto

• 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

Page 36: Whats New In C# 4 0 - NetPonto

COM Interop Improvements

Page 37: Whats New In C# 4 0 - NetPonto

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

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

COM Interop Improvements

Page 38: Whats New In C# 4 0 - NetPonto

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");

Page 39: Whats New In C# 4 0 - NetPonto

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];

Page 40: Whats New In C# 4 0 - NetPonto

Type Equivalence And Type Embedding (NO PIA)

Page 41: Whats New In C# 4 0 - NetPonto

• 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

Page 42: Whats New In C# 4 0 - NetPonto

Demos

Page 43: Whats New In C# 4 0 - NetPonto

Q & A

Page 44: Whats New In C# 4 0 - NetPonto

Conclusion

Page 45: Whats New In C# 4 0 - NetPonto

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

Conclusion

Page 46: Whats New In C# 4 0 - NetPonto

• 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

Page 47: Whats New In C# 4 0 - NetPonto

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

• LINQPad• http://linqpad.net/

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

Resources

Page 48: Whats New In C# 4 0 - NetPonto

Thank You!