Top Banner
What's new in C# 4.0? Ken Casada Developer Evangelist Microsoft Switzerland [email protected] http://blogs.msdn.com/swiss_dpe_team/Default. aspx
30
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Ken Casada Developer Evangelist Microsoft Switzerland kcasada@microsoft.com .

What's new in C# 4.0?

Ken CasadaDeveloper EvangelistMicrosoft [email protected]://blogs.msdn.com/swiss_dpe_team/Default.aspx

Page 2: Ken Casada Developer Evangelist Microsoft Switzerland kcasada@microsoft.com .

The Evolution of C#

C# 1.0

C# 2.0

C# 3.0

Managed Code

Generics

Language Integrated Query

Page 3: Ken Casada Developer Evangelist Microsoft Switzerland kcasada@microsoft.com .

Trends

Declarative

Concurrent

Dynamic

Page 4: Ken Casada Developer Evangelist Microsoft Switzerland kcasada@microsoft.com .

Declarative Programming

What

How

Imperative Declarative

Page 5: Ken Casada Developer Evangelist Microsoft Switzerland kcasada@microsoft.com .

Dynamic vs. Static

DynamicLanguages

Simple and succinct

Implicitly typed

Meta-programming

No compilation

StaticLanguages

Robust

Performant

Intelligent tools

Better scaling

Page 6: Ken Casada Developer Evangelist Microsoft Switzerland kcasada@microsoft.com .

Concurrency

Page 7: Ken Casada Developer Evangelist Microsoft Switzerland kcasada@microsoft.com .

Co-Evolution

Page 8: Ken Casada Developer Evangelist Microsoft Switzerland kcasada@microsoft.com .

The Evolution of C#

C# 1.0

C# 2.0

C# 3.0

Managed Code

Generics

Language Integrated Query

C# 4.0Dynamic Programming

Page 9: Ken Casada Developer Evangelist Microsoft Switzerland kcasada@microsoft.com .

Dynamically Typed ObjectsOptional and Named ParametersImproved COM InteroperabilityCo- and Contra-variance

C# 4.0 Language Innovations

Page 10: Ken Casada Developer Evangelist Microsoft Switzerland kcasada@microsoft.com .

PythonBinder

RubyBinder

COMBinder

JavaScript

Binder

ObjectBinder

.NET Dynamic Programming

Dynamic Language Runtime

Expression TreesDynamic Dispatch

Call Site Caching

IronPython

IronRuby C# VB.NET Others…

Page 11: Ken Casada Developer Evangelist Microsoft Switzerland kcasada@microsoft.com .

Dynamically Typed Objects

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

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

ScriptObject calc = GetCalculator();object res = calc.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 12: Ken Casada Developer Evangelist Microsoft Switzerland kcasada@microsoft.com .

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 13: Ken Casada Developer Evangelist Microsoft Switzerland kcasada@microsoft.com .

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

Dynamically Typed Objects

Method chosen at compile-time:

double Abs(double x)

Method chosen at run-time: double

Abs(double x)

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

Method chosen at run-time:

int Abs(int x)

Page 14: Ken Casada Developer Evangelist Microsoft Switzerland kcasada@microsoft.com .

Dynamically Typed Object

demo

Page 15: Ken Casada Developer Evangelist Microsoft Switzerland kcasada@microsoft.com .

IDynamicObject

public abstract class DynamicObject : IDynamicObject{ public virtual object GetMember(GetMemberBinder info); public virtual object SetMember(SetMemberBinder info, object value); public virtual object DeleteMember(DeleteMemberBinder info);  public virtual object UnaryOperation(UnaryOperationBinder info); public virtual object BinaryOperation(BinaryOperationBinder info, object arg); public virtual object Convert(ConvertBinder info);  public virtual object Invoke(InvokeBinder info, object[] args); public virtual object InvokeMember(InvokeMemberBinder info, object[] args); public virtual object CreateInstance(CreateInstanceBinder info, object[] args);  public virtual object GetIndex(GetIndexBinder info, object[] indices); public virtual object SetIndex(SetIndexBinder info, object[] indices, object value); public virtual object DeleteIndex(DeleteIndexBinder info, object[] indices);  public MetaObject IDynamicObject.GetMetaObject();}

Page 16: Ken Casada Developer Evangelist Microsoft Switzerland kcasada@microsoft.com .

Implementing IDynamicObject

demo

Page 17: Ken Casada Developer Evangelist Microsoft Switzerland kcasada@microsoft.com .

Optional and Named Parameters

public StreamReader OpenTextFile( string path, Encoding encoding, bool detectEncoding, int bufferSize);

public StreamReader OpenTextFile( string path, Encoding encoding, bool detectEncoding);

public StreamReader OpenTextFile( string path, Encoding encoding);

public StreamReader OpenTextFile( string path);

Primary method

Secondary overloads

Call primary with default values

Page 18: Ken Casada Developer Evangelist Microsoft Switzerland kcasada@microsoft.com .

Optional and Named Parameters

public StreamReader OpenTextFile( string path, Encoding encoding = null, bool detectEncoding = true, int bufferSize = 1024);

Optional parameters

OpenTextFile("foo.txt", Encoding.UTF8);OpenTextFile("foo.txt", Encoding.UTF8, bufferSize: 4096);

Named argument

OpenTextFile( bufferSize: 4096, path: "foo.txt", detectEncoding: false);

Named arguments must

be last

Non-optional must be specified

Arguments evaluated in order

written

Named arguments can appear in any

order

Page 19: Ken Casada Developer Evangelist Microsoft Switzerland kcasada@microsoft.com .

Improved COM Interoperability

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

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

doc.SaveAs("Test.docx");

Page 20: Ken Casada Developer Evangelist Microsoft Switzerland kcasada@microsoft.com .

Optional and named parametersOptional “ref” modifierInterop type embedding (“No PIA”)

Improved COM Interoperability

Page 21: Ken Casada Developer Evangelist Microsoft Switzerland kcasada@microsoft.com .

object dynamic mapping

Improved COM Interoperability

… you can now say

excel.Cells[1, 1].Value = "Hello";

instead of

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

… and

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

instead of

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

Page 22: Ken Casada Developer Evangelist Microsoft Switzerland kcasada@microsoft.com .

Co- and Contra-variance

void Process(object[] objects) { … }

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

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

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

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

.NET arrays are co-variant

…but not safely

co-variant

Until now, C# generics have

been invariant

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

C# 4.0 supports safe

co- and contra-

variance

Page 23: Ken Casada Developer Evangelist Microsoft Switzerland kcasada@microsoft.com .

Safe Co- and Contra-variance

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 = Co-variantOutput positions

only

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

Can be treated as

less derived

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 = Contra-variant

Input positions only

Can be treated as

more derived

Page 24: Ken Casada Developer Evangelist Microsoft Switzerland kcasada@microsoft.com .

Supported for interface and delegate typesValue types are always invariant

IEnumerable<int> is not IEnumerable<object>

Variance in C# 4.0

Page 25: Ken Casada Developer Evangelist Microsoft Switzerland kcasada@microsoft.com .

Variance in .NET Framework 4.0

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>

Interfaces

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

Delegates

Page 26: Ken Casada Developer Evangelist Microsoft Switzerland kcasada@microsoft.com .

The Evolution of C#

C# 1.0

C# 2.0

C# 3.0

Managed Code

Generics

Language Integrated Query

C# 4.0Dynamic Programming

Page 27: Ken Casada Developer Evangelist Microsoft Switzerland kcasada@microsoft.com .

C# 4.0 Samples and Whitepaperhttp://code.msdn.microsoft.com/csharpfuture

Visual C# Developer Centerhttp://csharp.net

C# team member’s blogshttp://blogs.msdn.com/ericlippert/http://blogs.msdn.com/cburrows/http://blogs.msdn.com/samng/http://blogs.msdn.com/sreekarc/ http://blogs.msdn.com/mattwar/http://blogs.msdn.com/ed_maurer/http://blogs.msdn.com/davsterl/ http://blogs.msdn.com/alexghi

Additional Resources

Page 28: Ken Casada Developer Evangelist Microsoft Switzerland kcasada@microsoft.com .

Save the date for tech·days next year!

14 – 15 avril 2010, CICG

Page 29: Ken Casada Developer Evangelist Microsoft Switzerland kcasada@microsoft.com .

Classic Sponsoring Partners

Premium Sponsoring Partners

Page 30: Ken Casada Developer Evangelist Microsoft Switzerland kcasada@microsoft.com .