introduction to c # – part 2 stephen turner software design engineer [email protected]...

34
Introduction to C Introduction to C # # Part 2 Part 2 Stephen Turner Stephen Turner Software Design Software Design Engineer Engineer [email protected] [email protected] om om Microsoft UK Microsoft UK

Upload: madeline-paula-hodges

Post on 02-Jan-2016

220 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Introduction to C # – Part 2 Stephen Turner Software Design Engineer sturner@microsoft.com Microsoft UK

Introduction to CIntroduction to C## – Part 2 – Part 2

Stephen TurnerStephen TurnerSoftware Design Software Design

[email protected]@microsoft.co

mmMicrosoft UKMicrosoft UK

Page 2: Introduction to C # – Part 2 Stephen Turner Software Design Engineer sturner@microsoft.com Microsoft UK

AgendaAgenda

Design goals – Part 2Design goals – Part 2 Fully extensible type systemFully extensible type system Enable robust and durable applicationsEnable robust and durable applications Leverage existing softwareLeverage existing software

StandardizationStandardization

Page 3: Introduction to C # – Part 2 Stephen Turner Software Design Engineer sturner@microsoft.com Microsoft UK

Extending the Type SystemExtending the Type System

Most users think of two types of objectsMost users think of two types of objects ““Real” objects – Customer, Order, etc.Real” objects – Customer, Order, etc. Primitive types – int, float, boolPrimitive types – int, float, bool

Different expectations for eachDifferent expectations for each Real objects are more expensive to createReal objects are more expensive to create Primitives always have a valuePrimitives always have a value Primitives have operator supportPrimitives have operator support

Classes and Structs – Classes and Structs – bbest of both est of both worlds!worlds!Natural semantics Natural semantics Operator overloadingOperator overloading & & User conversionsUser conversions

Interface supportInterface support

Page 4: Introduction to C # – Part 2 Stephen Turner Software Design Engineer sturner@microsoft.com Microsoft UK

Rational Numbers (½, ¾, Rational Numbers (½, ¾, 1½)1½)Rational r1 = new Rational(1,2);Rational r2 = new Rational(2,1);

Rational r3 = r1.AddRational(r2);

double d = Rational.ConvertToDouble(r3);

Rational r1 = new Rational(1,2);Rational r2 = 2;

Rational r3 = r1 + r2;

double d = (double) r3;

Page 5: Introduction to C # – Part 2 Stephen Turner Software Design Engineer sturner@microsoft.com Microsoft UK

Rational Number – Class?Rational Number – Class?

Heap allocatedHeap allocatedCan be null Can be null ““=” assigns reference not value=” assigns reference not valueArrays allocate references not valuesArrays allocate references not values

public class Rational {

public Rational(int n, int d) { … } }

Rational[] array = new Rational[100];

Page 6: Introduction to C # – Part 2 Stephen Turner Software Design Engineer sturner@microsoft.com Microsoft UK

Structs Provide an AnswerStructs Provide an Answer

Behavior differences versus ClassesBehavior differences versus Classes Stored in-line, not heap allocatedStored in-line, not heap allocated Never nullNever null Assignment copies data, not referenceAssignment copies data, not reference

Implementation differencesImplementation differences Always inherit from objectAlways inherit from object Always has a default constructorAlways has a default constructor

Page 7: Introduction to C # – Part 2 Stephen Turner Software Design Engineer sturner@microsoft.com Microsoft UK

Rational Number – StructRational Number – Struct

public struct Rational{

public Rational(int n, int d) { … }

public int Numerator { get{…} }public int Denominator { get{…} }

public override string ToString() { … }}

Rational r = new Rational(1,2);

string s = r.ToString();

Page 8: Introduction to C # – Part 2 Stephen Turner Software Design Engineer sturner@microsoft.com Microsoft UK

Implicit ConversionsImplicit Conversions

No loss of dataNo loss of data

public struct Rational{

…public static implicit operator Rational(int i){

return new Rational(i,1);}

}

Rational r = 2;

Page 9: Introduction to C # – Part 2 Stephen Turner Software Design Engineer sturner@microsoft.com Microsoft UK

Explicit ConversionsExplicit Conversions

Possible loss of precision and can throw Possible loss of precision and can throw exceptionsexceptions

public struct Rational{

…public static explicit operator double(Rational r){

return (double) r.Numerator / r.Denominator;}

}

Rational r = new Rational(2,3);double d = (double) r;

Page 10: Introduction to C # – Part 2 Stephen Turner Software Design Engineer sturner@microsoft.com Microsoft UK

Operator Overloading Operator Overloading

Static operatorsStatic operatorsMust take its type as a parameterMust take its type as a parameter

public struct Rational{

…public static Rational operator+ (

Rational lhs, Rational rhs) {

return new Rational( … );}

}

Rational r3 = r1 + r2;

r3 += 2;

Page 11: Introduction to C # – Part 2 Stephen Turner Software Design Engineer sturner@microsoft.com Microsoft UK

Equality OperatorsEquality Operators

.NET Framework equality support .NET Framework equality support

.Equals() should use operator==().Equals() should use operator==()

public override bool Equals(object o)

public static bool operator== (Rational lhs, Rational rhs) public static bool operator!= (Rational lhs, Rational rhs)

if ( r1.Equals(r2) ) { … }if ( !r1.Equals(r2)) { … }

if ( r1 == r2 ) { … } if ( r1 != r2 ) { … }

Page 12: Introduction to C # – Part 2 Stephen Turner Software Design Engineer sturner@microsoft.com Microsoft UK

Structs and InterfacesStructs and Interfaces

Structs can implement interfaces to Structs can implement interfaces to provide additional functionality provide additional functionality Why? The same reasons classes can!Why? The same reasons classes can!ExamplesExamples System.IComparableSystem.IComparable

Search and sort support in collectionsSearch and sort support in collections System.IFormattableSystem.IFormattable

Placeholder formattingPlaceholder formatting

Page 13: Introduction to C # – Part 2 Stephen Turner Software Design Engineer sturner@microsoft.com Microsoft UK

System.IFormattableSystem.IFormattable

Types can support new formatting Types can support new formatting options through IFormattable options through IFormattable

Rational r1 = new Rational(2,4);

Console.WriteLine(“Rational {0}", r1); Console.WriteLine(“Rational {0:reduced}", r1);

Page 14: Introduction to C # – Part 2 Stephen Turner Software Design Engineer sturner@microsoft.com Microsoft UK

Implementing IFormattableImplementing IFormattable

public struct Rational : IFormattable {public string Format(

string formatStr, IServiceObjectProvider isop) { s = this.ToString(); if ( formatStr == “reduced" ) { s = … } return s;

}}

Rational r1 = new Rational(2,4); Console.WriteLine("No Format = {0}", r1);Console.WriteLine("Reduced Format = {0:reduced}", r1);

No Format = 2/4Reduced Format = 1/2

Page 15: Introduction to C # – Part 2 Stephen Turner Software Design Engineer sturner@microsoft.com Microsoft UK

AgendaAgenda

Design goals – Part 2Design goals – Part 2 Fully extensible type systemFully extensible type system Enable robust and durable applicationsEnable robust and durable applications Leverage existing softwareLeverage existing software

StandardizationStandardization

Page 16: Introduction to C # – Part 2 Stephen Turner Software Design Engineer sturner@microsoft.com Microsoft UK

Robust and Durable Robust and Durable SoftwareSoftware

Garbage collectionGarbage collection No memory leaks and stray pointersNo memory leaks and stray pointers

ExceptionsExceptions Error handling is not an afterthoughtError handling is not an afterthought

Type-safetyType-safety No uninitialized variables, unsafe castsNo uninitialized variables, unsafe casts

VersioningVersioning Pervasive versioning considerations in all Pervasive versioning considerations in all

aspects of language designaspects of language design

Page 17: Introduction to C # – Part 2 Stephen Turner Software Design Engineer sturner@microsoft.com Microsoft UK

Language Safety vs. C++Language Safety vs. C++

If, while, do require bool conditionIf, while, do require bool conditionGoto can’t jump into blocksGoto can’t jump into blocksSwitch statementSwitch statement No fall-throughNo fall-through Break, goto <case> or goto defaultBreak, goto <case> or goto default

Checked and unchecked statementsChecked and unchecked statementsExpression statements must do workExpression statements must do work

void Foo() {i == 1; // error

}

Page 18: Introduction to C # – Part 2 Stephen Turner Software Design Engineer sturner@microsoft.com Microsoft UK

VersioningVersioning

Overlooked in most languagesOverlooked in most languages C++ and Java produce fragile base C++ and Java produce fragile base

classes classes Users unable to express versioning intentUsers unable to express versioning intent

C# allows intent to be expressedC# allows intent to be expressed Methods are not virtual by defaultMethods are not virtual by default C# keywords “virtual”, “override” and C# keywords “virtual”, “override” and

“new” provide context“new” provide context

But C# can't guarantee versioningBut C# can't guarantee versioning Can enable (e.g., explicit override)Can enable (e.g., explicit override) Can encourage (e.g., smart defaults)Can encourage (e.g., smart defaults)

Page 19: Introduction to C # – Part 2 Stephen Turner Software Design Engineer sturner@microsoft.com Microsoft UK

Method Versioning in JavaMethod Versioning in Java

class Derived extends Base // v1.0class Derived extends Base // v1.0{{ public void Foo() public void Foo() {{ System.out.println("Derived.Foo"); System.out.println("Derived.Foo"); }}}}

class Base // v1.0class Base // v1.0{{}}

class Base class Base // v2.0 // v2.0 {{ public void Foo() public void Foo() {{ Database.Log("Base.Foo"); Database.Log("Base.Foo"); }}}}

class Base class Base // v2.0 // v2.0 {{ public public intint Foo() Foo() {{ Database.Log("Base.Foo"); Database.Log("Base.Foo"); }}}}

Page 20: Introduction to C # – Part 2 Stephen Turner Software Design Engineer sturner@microsoft.com Microsoft UK

Method Versioning in C#Method Versioning in C#

class Derived : Base // v1.0class Derived : Base // v1.0{{ public virtual void Foo() public virtual void Foo() {{ Console.WriteLine("Derived.Foo"); Console.WriteLine("Derived.Foo"); }}}}

class Base // v1.0class Base // v1.0{{}}

class Base class Base // v2.0 // v2.0 {{ public virtual void Foo() public virtual void Foo() {{ Database.Log("Base.Foo"); Database.Log("Base.Foo"); }}}}

class Base class Base // v2.0 // v2.0 {{ public virtual public virtual intint Foo() Foo() {{ Database.Log("Base.Foo"); return 0; Database.Log("Base.Foo"); return 0; }}}}

class Derived : Base // v2.0class Derived : Base // v2.0{{ public public newnew virtual void Foo() virtual void Foo() {{ Console.WriteLine("Derived.Foo"); Console.WriteLine("Derived.Foo"); }}}}

class Derived : Base // v2.0class Derived : Base // v2.0{{ public public overrideoverride void Foo() void Foo() {{ super.Foo();super.Foo(); Console.WriteLine("Derived.Foo"); Console.WriteLine("Derived.Foo"); }}}}

Page 21: Introduction to C # – Part 2 Stephen Turner Software Design Engineer sturner@microsoft.com Microsoft UK

AgendaAgenda

Design goals – Part 2Design goals – Part 2 Fully extensible type systemFully extensible type system Enable robust and durable applicationsEnable robust and durable applications Leverage existing softwareLeverage existing software

StandardizationStandardization

Page 22: Introduction to C # – Part 2 Stephen Turner Software Design Engineer sturner@microsoft.com Microsoft UK

Calling Into Existing DLLsCalling Into Existing DLLsRuntime enables calling “C-Style” Runtime enables calling “C-Style” functionsfunctionsFeature known as “Platform Invoke”Feature known as “Platform Invoke”Attributes define how things workAttributes define how things work

Which library to useWhich library to use [DllImport][DllImport]How to marshal dataHow to marshal data [MarshalAs][MarshalAs]Structure layout in Structure layout in memorymemory

[StructLayout][StructLayout][FieldOffset][FieldOffset]

Page 23: Introduction to C # – Part 2 Stephen Turner Software Design Engineer sturner@microsoft.com Microsoft UK

DLL Import ExamplesDLL Import Examples

[DllImport("gdi32.dll", CharSet=CharSet.Auto)]

public static extern int GetObject(int hObject, int nSize, [In, Out] ref LOGFONT lf);

[DllImport("gdi32.dll")]

public static extern int CreatePen(int style, int width, int color);

Page 24: Introduction to C # – Part 2 Stephen Turner Software Design Engineer sturner@microsoft.com Microsoft UK

Platform Invoke LimitationsPlatform Invoke Limitations

Marshaler can’t handle every caseMarshaler can’t handle every case Ugly dealing with memory allocationUgly dealing with memory allocation Complex structures can’t be marshalledComplex structures can’t be marshalled

Complex P/Invoke is hard to debugComplex P/Invoke is hard to debug Play “convince the marshaller”…Play “convince the marshaller”…

Can’t use C++ objectsCan’t use C++ objectsCan waste lots of time and effortCan waste lots of time and effort Did I say it was tough to debug?Did I say it was tough to debug?

Solution:Solution: Use unsafe C# or Managed C++Use unsafe C# or Managed C++

Page 25: Introduction to C # – Part 2 Stephen Turner Software Design Engineer sturner@microsoft.com Microsoft UK

COM SupportCOM Support

.NET Framework provides great COM .NET Framework provides great COM support support TLBIMP imports existing COM classesTLBIMP imports existing COM classes TLBEXP exports .NET typesTLBEXP exports .NET types

Sometimes you need more control Sometimes you need more control Methods taking complicated structures Methods taking complicated structures Large TLB – only using a few classesLarge TLB – only using a few classes

System.Runtime.InteropservicesSystem.Runtime.Interopservices COM object identificationCOM object identification Parameter and return value marshallingParameter and return value marshalling HRESULT behaviorHRESULT behavior

Page 26: Introduction to C # – Part 2 Stephen Turner Software Design Engineer sturner@microsoft.com Microsoft UK

COM SupportCOM Support

Sometimes you need more control Sometimes you need more control Methods with complicated structures Methods with complicated structures

as argumentsas arguments Large TLB – only using a few classesLarge TLB – only using a few classes

System.Runtime.InteropServicesSystem.Runtime.InteropServices COM object identificationCOM object identification Parameter and return value marshallingParameter and return value marshalling HRESULT behaviorHRESULT behavior

Page 27: Introduction to C # – Part 2 Stephen Turner Software Design Engineer sturner@microsoft.com Microsoft UK

COM Support ExampleCOM Support Example[Guid(“56A868B1-0AD4-11CE-B03A-0020AF0BA770”)] interface IMediaControl { void Run(); void Pause(); void Stop(); … void RenderFile(string strFilename);}

Page 28: Introduction to C # – Part 2 Stephen Turner Software Design Engineer sturner@microsoft.com Microsoft UK

Unsafe Code – PointersUnsafe Code – Pointers

Developers sometime need total Developers sometime need total controlcontrol Performance extremesPerformance extremes Dealing with existing binary structuresDealing with existing binary structures Advanced COM Support, DLL ImportAdvanced COM Support, DLL Import

C# “unsafe” = limited “inline C”C# “unsafe” = limited “inline C” Pointer types, pointer arithmeticPointer types, pointer arithmetic unsafe castsunsafe casts Declarative pinning (fixed statement)Declarative pinning (fixed statement)

Power comes at a price!Power comes at a price! Unsafe means unverifiable codeUnsafe means unverifiable code

Page 29: Introduction to C # – Part 2 Stephen Turner Software Design Engineer sturner@microsoft.com Microsoft UK

Unsafe Code & P/InvokeUnsafe Code & P/Invoke

class FileStream: Stream {

int handle;

public unsafe int Read(byte[] buffer, int index, int count) {

int n = 0;fixed (byte* p = buffer) {

ReadFile(handle, p + index, count, &n, null);}return n;

}

[dllimport("kernel32", SetLastError=true)]static extern unsafe bool ReadFile(

int hFile, void* lpBuffer, int nBytesToRead,int* nBytesRead, Overlapped* lpOverlapped);

}

Page 30: Introduction to C # – Part 2 Stephen Turner Software Design Engineer sturner@microsoft.com Microsoft UK

AgendaAgenda

Extending the type systemExtending the type system Creating a fully functional rational number Creating a fully functional rational number

typetype

Enable robust and durable applicationsEnable robust and durable applications Language safety & code versioningLanguage safety & code versioning

Leverage existing software investmentLeverage existing software investment COM & DLL interopCOM & DLL interop Unsafe code and pointersUnsafe code and pointers

StandardizationStandardization

Page 31: Introduction to C # – Part 2 Stephen Turner Software Design Engineer sturner@microsoft.com Microsoft UK

C# and CLI StandardizationC# and CLI Standardization

Work begun in September 2000Work begun in September 2000 Intel, HP, IBM, Fujitsu, Plum Hall, and othersIntel, HP, IBM, Fujitsu, Plum Hall, and others

ECMA ratified in December 2001ECMA ratified in December 2001ISO ratified in April 2003ISO ratified in April 2003Several CLI and C# implementationsSeveral CLI and C# implementations .NET Framework and Visual Studio .NET.NET Framework and Visual Studio .NET SSCLI – Shared source on XP, FreeBSD, OS XSSCLI – Shared source on XP, FreeBSD, OS X Mono – Open source on LinuxMono – Open source on Linux

Standardization of new features ongoingStandardization of new features ongoing

Page 32: Introduction to C # – Part 2 Stephen Turner Software Design Engineer sturner@microsoft.com Microsoft UK

Useful ResourcesUseful Resources

Web sitesWeb sites http://www.gotdotnet.com/team/csharphttp://www.gotdotnet.com/team/csharp http://msdn.microsoft.com/vcsharphttp://msdn.microsoft.com/vcsharp http://msdn.microsoft.com/netframeworkhttp://msdn.microsoft.com/netframework

NewsgroupsNewsgroups http://msdn.microsoft.com/newsgroupshttp://msdn.microsoft.com/newsgroups microsoft.public.dotnet.languages.csharpmicrosoft.public.dotnet.languages.csharp

BooksBooks C# Language Specification” – MS PressC# Language Specification” – MS Press Inside C# – MS PressInside C# – MS Press

Page 33: Introduction to C # – Part 2 Stephen Turner Software Design Engineer sturner@microsoft.com Microsoft UK

C# MomentumC# MomentumOver 50 trade books publishedOver 50 trade books published O’Reilly, Addison-Wesley, Prentice Hall, O’Reilly, Addison-Wesley, Prentice Hall,

APress, Osborne, Sams, Wrox, MS PressAPress, Osborne, Sams, Wrox, MS Press

Over 15 dedicated Web sitesOver 15 dedicated Web sites http://www.csharp-station.comhttp://www.csharp-station.com http://www.csharphelp.comhttp://www.csharphelp.com http://www.csharptoday.comhttp://www.csharptoday.com http://www.csharpindex.comhttp://www.csharpindex.com

Other site can be found atOther site can be found at http://msdn.microsoft.com/communityhttp://msdn.microsoft.com/community

Page 34: Introduction to C # – Part 2 Stephen Turner Software Design Engineer sturner@microsoft.com Microsoft UK

© 2003 Microsoft Ltd. All rights reserved.© 2003 Microsoft Ltd. All rights reserved.This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.