C# 4.0

Post on 10-May-2015

1.048 views 1 download

Tags:

description

Børge Hansen presenterte C# 4.0 og .Net 4.0 på høstens runde av MSDN & TechNet Live.

Transcript of C# 4.0

C# 4.0og .Net 4.0

Børge Hansen

borge@devpartner.no

http://borge3000.no

Functional

Concise

Declarative

Before

IList<Person> FindParentsWithChildNamed(string childName)

{

var matches = new List<Person>();

foreach(var person in _people)

{

foreach(var child in person.Children)

{

if (child.Name.Equals(childName))

{

matches.Add(person);

break;

}

}

}

return matches;

}

LINQ, The Power of Declarative

IList<Person> FindParentsWithChildNamed(string childName) {

var matches = from person in peoplefrom child in person.Childrenwhere child.Name.Equals(childName)select person;

return matches.ToList();}

After

LINQ, The Power of Declarative

Why Declarative Matters…

Imperative Declarative

What

How

Addressing Language Trends

Declarative

ConcurrentDynamic

The Evolution of C#

C# 1.0

C# 2.0

C# 3.0

Managed Code

Generics

LINQ

C# 4.0

Dynamic

New C# 4.0 Features

1. Late-Binding Support / dynamic lookup

2. Named and Optional Parameters

3. Improved COM Interop

4. Covariance and Contravariance

Dynamically Typed Objects

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

Compile-time typedynamic

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

DEMOC# 4.0 features:Dynamic keyword

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

Optional and Named Parameters

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

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

DEMOC# 4.0 features:Named and optional parameters

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

• Automatic object dynamic mapping• Optional and named parameters• Indexed properties• Optional “ref” modifier• Interop type embedding (“No PIA”)

Improved COM Interoperability

DEMOC# 4.0 features:Com Interop

string GetDescription(int x);

/// <param name=“x”>/// should be greater than zero/// </param>/// <returns>/// non-null string/// </returns>string GetDescription(int x);

How Do You Know What It Does?string s = o.GetDescription(i);… s.Length …

Let’s Fix It For Once And All!

string GetDescription(int x) {Contract.Requires( 0 < x );Contract.Ensures(

Contract.Result<string>()!= null );

…}

Design-by-Contract meets .NET!

• Contracts document design decisions– Preconditions, postconditions, invariants– Facilitate code evolution

• Contracts are executable– Checked documentation– Test oracles

• Contracts help static verification– Early error detection– Clarify responsibility at API boundaries

• Assertions help, but everyone has their own flavor– Difficult to tool against– Not seen as a contract between 2 parties

Contracts

class Rational {

public Rational(int n, int d) {Contract.Requires( 0 < d );this.N = n;this.D = d;

}}

What Can I Do With Contracts?

Documentation

Runtime

Checking

Static Checking

Test

Generation(Pex)

• Requires– What must be true at method entry

• Ensures– What must be true at method exit

• Invariants– What must be true at all method exits

• Assertions– What must be true at a particular point

• Assumptions– What should be true at a particular point

What Contracts Can I Write?

• Any boolean expression– In your favorite programming language!– Including method calls (but must

be marked Pure)

• Quantifiers– Contract.ForAll(0,A.Length,i => A[i] > 0);– Contract.Exists(0,A.Length,i => A[i] > 0);

• Contract.Result– refer to the return value of the method

• Contract.OldValue– refer to values at method entry

What Can I Put In A Contract?

DEMOC# 4.0 features:Code contracts

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

• Visual C# Developer Centerhttp://csharp.net

• Visual Studio 2010 Training kithttp://www.microsoft.com/downloads/details.aspx?FamilyID=752cb725-

969b-4732-a383-ed5740f02e93&DisplayLang=en

• Code contractshttp://research.microsoft.com/en-

us/projects/contracts

Additional Resources

Børge Hansenborge@devpartner.nohttp://borge3000.no

+47 905 905 38