Object Oriented Programming in C# Keith Pijanowski.Net Developer Evangelist [email protected]...

43
Object Oriented Object Oriented Programming in C# Programming in C# Keith Pijanowski Keith Pijanowski .Net Developer Evangelist .Net Developer Evangelist [email protected] [email protected] Microsoft Corporation Microsoft Corporation

Transcript of Object Oriented Programming in C# Keith Pijanowski.Net Developer Evangelist [email protected]...

Object Oriented Object Oriented Programming in C#Programming in C#

Keith PijanowskiKeith Pijanowski.Net Developer Evangelist.Net Developer [email protected]@microsoft.comMicrosoft CorporationMicrosoft Corporation

AgendaAgenda

OverviewOverview Program StructureProgram Structure Value Types and Reference TypesValue Types and Reference Types Base Classes, Derived Classes, Abstract Base Classes, Derived Classes, Abstract

Classes, & InterfacesClasses, & Interfaces Delegates and EventsDelegates and Events Operator OverloadingOperator Overloading VersioningVersioning

The .NET FrameworkThe .NET FrameworkOverviewOverview

Base Class LibraryBase Class Library

Common Language SpecificationCommon Language Specification

Common Language RuntimeCommon Language Runtime

ADO.NET: Data and XMLADO.NET: Data and XML

VBVB C++C++ C#C#

Visu

al Stu

dio

.NE

TV

isual S

tud

io.N

ET

ASP.NET: Web ServicesASP.NET: Web ServicesAnd Web FormsAnd Web Forms

JScriptJScript ……

WindowsWindowsformsforms

AgendaAgenda

OverviewOverview Program StructureProgram Structure Value Types and Reference TypesValue Types and Reference Types Base Classes, Derived Classes, Abstract Base Classes, Derived Classes, Abstract

Classes, & InterfacesClasses, & Interfaces Delegates and EventsDelegates and Events Operator OverloadingOperator Overloading VersioningVersioning

Program StructureProgram StructureLevelsLevels

NamespacesNamespaces Contain types and other namespacesContain types and other namespaces

Type declarationsType declarations Classes, structs, interfaces, enums, Classes, structs, interfaces, enums,

and delegatesand delegates MembersMembers

Constants, fields, methods, properties, indexers, Constants, fields, methods, properties, indexers, events, operators, constructors, destructorsevents, operators, constructors, destructors

OrganizationOrganization No header files, code written “in-line”No header files, code written “in-line” No declaration order dependenceNo declaration order dependence

Program StructureProgram StructureNamespacesNamespaces

Declare a scopeDeclare a scope Organize CodeOrganize Code Globally Unique TypesGlobally Unique Types Using {Using {Some NamespaceSome Namespace}}

Imports the type members of a namespace.Imports the type members of a namespace.

Program StructureProgram Structure ExampleExampleusing System;using System;

namespace System.Collectionsnamespace System.Collections{{ public class Stackpublic class Stack {{ Entry top;Entry top;

public void Push(object data) public void Push(object data) {{ top = new Entry(top, data);top = new Entry(top, data); }}

public object Pop() public object Pop() {{ if (top == null) throw new InvalidOperationException();if (top == null) throw new InvalidOperationException(); object result = top.data;object result = top.data; top = top.next;top = top.next; return result;return result; }} }}}}

AgendaAgenda

OverviewOverview Program StructureProgram Structure Value Types and Reference TypesValue Types and Reference Types Base Classes, Derived Classes, Abstract Base Classes, Derived Classes, Abstract

Classes, & InterfacesClasses, & Interfaces Delegates and EventsDelegates and Events Operator OverloadingOperator Overloading VersioningVersioning

Value and Reference TypesValue and Reference Types DefinitionDefinition

Value typesValue types Directly contain dataDirectly contain data Cannot be nullCannot be null

Reference typesReference types Contain references to objectsContain references to objects May be nullMay be null

int i = 123;int i = 123;string s = "Hello world";string s = "Hello world";

123123ii

ss "Hello world""Hello world"

Value and Reference TypesValue and Reference Types ExampleExample

Value typesValue types PrimitivesPrimitives int i;int i; EnumsEnums enum State { Off, enum State { Off,

On }On } StructsStructs struct Point { int x, struct Point { int x,

y; }y; } Reference typesReference types

ClassesClasses class Foo: Bar, IFoo class Foo: Bar, IFoo {...}{...}

InterfacesInterfaces interface IFoo: IBar interface IFoo: IBar {...}{...}

ArraysArrays string[] a = new string[] a = new string[10];string[10];

DelegatesDelegates delegate void delegate void Empty();Empty();

Value and Reference TypesValue and Reference Types ClassesClasses

Single inheritanceSingle inheritance Multiple interface implementationMultiple interface implementation Class membersClass members

Constants, fields, methods, Constants, fields, methods, properties, indexers, events, properties, indexers, events, operators, constructors, destructorsoperators, constructors, destructors

Static and instance membersStatic and instance members Nested typesNested types

Member accessMember access Public, protected, internal, privatePublic, protected, internal, private

Value and Reference TypesValue and Reference Types StructsStructs

Like classes, exceptLike classes, except Stored in-line, not heap allocatedStored in-line, not heap allocated Assignment copies data, not referenceAssignment copies data, not reference No inheritanceNo inheritance

Ideal for light weight objectsIdeal for light weight objects Complex, point, rectangle, colorComplex, point, rectangle, color int, float, double, etc., are all structsint, float, double, etc., are all structs

BenefitsBenefits No heap allocation, less GC pressureNo heap allocation, less GC pressure More efficient use of memoryMore efficient use of memory

Value and Reference TypesValue and Reference Types Classes and StructsClasses and Structs

class CPoint { int x, y; ... }class CPoint { int x, y; ... }struct SPoint { int x, y; ... }struct SPoint { int x, y; ... }

CPoint cp = new CPoint(10, 20);CPoint cp = new CPoint(10, 20);SPoint sp = new SPoint(10, 20);SPoint sp = new SPoint(10, 20);

1010

2020spsp

cpcp

1010

2020

CPointCPoint

Value and Reference TypesValue and Reference TypesUnified Type SystemUnified Type System

Everything is an objectEverything is an object All types ultimately inherit from objectAll types ultimately inherit from object Any piece of data can be stored, Any piece of data can be stored,

transported, and manipulated with no transported, and manipulated with no extra workextra work

StreamStream

MemoryStreamMemoryStream FileStreamFileStream

HashtableHashtable doubledoubleintint

objectobject

Value and Reference TypesValue and Reference TypesBoxing and UnboxingBoxing and Unboxing

BoxingBoxing Allocates box, copies value into itAllocates box, copies value into it

UnboxingUnboxing Checks type of box, copies value outChecks type of box, copies value out

int i = 123;int i = 123;object o = i;object o = i;int j = (int)o;int j = (int)o;

123123i

o

123123

System.Int32System.Int32

123123j

Language FeaturesLanguage FeaturesUnified Type SystemUnified Type System

BenefitsBenefits Eliminates “wrapper classes”Eliminates “wrapper classes” Collection classes work with all typesCollection classes work with all types Replaces OLE Automation's VariantReplaces OLE Automation's Variant

Lots of examples in .NET frameworkLots of examples in .NET framework

string s = string.Format(string s = string.Format( "Your total was {0} on {1}", total, date);"Your total was {0} on {1}", total, date);

Hashtable t = new Hashtable();Hashtable t = new Hashtable();t.Add(0, "zero");t.Add(0, "zero");t.Add(1, "one");t.Add(1, "one");t.Add(2, "two");t.Add(2, "two");

Demonstration 1Demonstration 1

Program StructureProgram StructureValue TypesValue Types

Reference TypesReference Types

AgendaAgenda

OverviewOverview Program StructureProgram Structure Value Types and Reference TypesValue Types and Reference Types Base Classes, Derived Classes, Abstract Base Classes, Derived Classes, Abstract

Classes, & InterfacesClasses, & Interfaces Delegates and EventsDelegates and Events Operator OverloadingOperator Overloading VersioningVersioning

Base ClassesBase Classes DefinitionDefinition Synonymous with SuperclassSynonymous with Superclass Derived Classes are created from Base Derived Classes are created from Base

classes.classes. Base classes may also be derived Base classes may also be derived

classesclasses KeywordsKeywords

privateprivate publicpublic internalinternal protectedprotected virtualvirtual

Derived ClassesDerived Classes DefinitionDefinition Synonymous with SubclassSynonymous with Subclass Single InheritanceSingle Inheritance Extend base class functionalityExtend base class functionality Replace base class functionalityReplace base class functionality Augment existing functionalityAugment existing functionality KeywordsKeywords

privateprivate publicpublic internalinternal protectedprotected overrideoverride basebase sealedsealed

Base & Derived ClassesBase & Derived Classes SyntaxSyntax

public class Mammalpublic class Mammal{{ public void Breathe() {…}public void Breathe() {…} public virtual void Walk() {…}public virtual void Walk() {…} public virtual void Eat() {…}public virtual void Eat() {…}}}

public class Dog: Mammalpublic class Dog: Mammal{{ override public void Walk() {…}override public void Walk() {…} public string Bark() {…}public string Bark() {…}}}

Abstract ClassesAbstract Classes DefinitionDefinition

A base class that can not be createdA base class that can not be created Must be overriddenMust be overridden KeywordsKeywords

privateprivate publicpublic internalinternal protectedprotected virtualvirtual abstract (class and member level)abstract (class and member level)

Abstract & Derived ClassesAbstract & Derived Classes ExampleExample

public abstract class Mammalpublic abstract class Mammal{{ public void Breathe() {…}public void Breathe() {…} public virtual void Walk() {…}public virtual void Walk() {…} public virtual void Eat() {…}public virtual void Eat() {…} public abstract bool Swim()public abstract bool Swim()}}

public class Dog: Mammalpublic class Dog: Mammal{{ override public void Walk() {…}override public void Walk() {…} public string Bark() {…}public string Bark() {…} override public bool Swim() {return false;}override public bool Swim() {return false;}}}

InterfacesInterfaces DefinitionDefinition

Multiple inheritanceMultiple inheritance Can contain methods, properties, Can contain methods, properties,

indexers and eventsindexers and events Provides polymorphic behaviorProvides polymorphic behavior Does not represent an ‘is-a’ relationshipDoes not represent an ‘is-a’ relationship Represents a contract between classesRepresents a contract between classes

InterfacesInterfaces SyntaxSyntax

interface IDataBoundinterface IDataBound{{ void Bind(IDataBinder binder);void Bind(IDataBinder binder);}}

class EditBox: Control, IDataBoundclass EditBox: Control, IDataBound{{ void IDataBound.Bind(IDataBinder binder) {...}void IDataBound.Bind(IDataBinder binder) {...}}}

InterfacesInterfaces Interfaces in the .NET FrameworkInterfaces in the .NET Framework

IComparableIComparable IEnumerable and IEnumeratorIEnumerable and IEnumerator IFormattableIFormattable IListIList ICloneableICloneable IComponentIComponent IDataErrorInfoIDataErrorInfo

Demonstration 2Demonstration 2

Base ClassesBase ClassesDerived ClassesDerived ClassesAbstract ClassesAbstract Classes

InterfacesInterfaces

AgendaAgenda

OverviewOverview Program StructureProgram Structure Value Types and Reference TypesValue Types and Reference Types Base Classes, Derived Classes, Abstract Base Classes, Derived Classes, Abstract

Classes, & InterfacesClasses, & Interfaces Delegates and EventsDelegates and Events Operator OverloadingOperator Overloading VersioningVersioning

DelegatesDelegates DefinitionDefinition

Object oriented function pointersObject oriented function pointers Multiple receiversMultiple receivers

Each delegate has an invocation listEach delegate has an invocation list Thread-safe + and - operationsThread-safe + and - operations

Foundation for framework eventsFoundation for framework events

delegate void MouseEvent(int x, int y);delegate void MouseEvent(int x, int y);

delegate double Func(double x);delegate double Func(double x);

Func MyFunc = new Func(Math.Sin);Func MyFunc = new Func(Math.Sin);double x = MyFunc(1.0);double x = MyFunc(1.0);

DelegatesDelegates SyntaxSyntax

public delegate void MouseEvent(int x, int y);public delegate void MouseEvent(int x, int y);

public delegate double Func(double x);public delegate double Func(double x);

Func MyFunc = new Func(Math.Sin);Func MyFunc = new Func(Math.Sin);double x = MyFunc(1.0);double x = MyFunc(1.0);

Custom EventsCustom Events Creating, Firing and HandleCreating, Firing and Handle Event signature and firing logicEvent signature and firing logic

Handling the EventHandling the Event

public class MyClasspublic class MyClass{{ public delegate void MyHandler(EventArgs e);public delegate void MyHandler(EventArgs e); public event MyHandler MyEvent;public event MyHandler MyEvent;

if (MyEvent != null) MyEvent(e);if (MyEvent != null) MyEvent(e);}}

public event EventHandler Click;public event EventHandler Click; MyClass obj = new MyClass();MyClass obj = new MyClass(); obj.MyEvent += new MyClass.MyHandler(MyFunc);obj.MyEvent += new MyClass.MyHandler(MyFunc);

Events Events System.EventHandlerSystem.EventHandler

Define and register Event HandlerDefine and register Event Handler

public class MyForm: Formpublic class MyForm: Form{{ Button okButton;Button okButton;

public MyForm() public MyForm() {{ okButton = new Button(...);okButton = new Button(...); okButton.Caption = "OK";okButton.Caption = "OK"; okButton.Click += new EventHandler(OkButtonClick);okButton.Click += new EventHandler(OkButtonClick); }}

void OkButtonClick(object sender, EventArgs e) void OkButtonClick(object sender, EventArgs e) {{ ShowMessage("You pressed the OK button");ShowMessage("You pressed the OK button"); }}}}

Demonstration 3Demonstration 3

DelegatesDelegatesEventsEvents

AgendaAgenda

OverviewOverview Program StructureProgram Structure Value Types and Reference TypesValue Types and Reference Types Base Classes, Derived Classes, Abstract Base Classes, Derived Classes, Abstract

Classes, & InterfacesClasses, & Interfaces Delegates and EventsDelegates and Events Operator OverloadingOperator Overloading VersioningVersioning

Operator OverloadingOperator Overloading DefinitionDefinition

Allows for the specification of an Allows for the specification of an operator in the context of a class you operator in the context of a class you have defined.have defined.

Binary OperatorsBinary Operators Unary OperatorsUnary Operators Implicit type ConversionsImplicit type Conversions Explicit type conversionsExplicit type conversions Only available in C#, not VB.NETOnly available in C#, not VB.NET

Operator OverloadingOperator Overloading SyntaxSyntax

public struct DBIntpublic struct DBInt{{

………………..

public static DBInt operator +(DBInt x, DBInt y) {...}public static DBInt operator +(DBInt x, DBInt y) {...}

public static implicit operator DBInt(int x) {...}public static implicit operator DBInt(int x) {...} public static explicit operator int(DBInt x) {...}public static explicit operator int(DBInt x) {...}}}

DBInt x = 123;DBInt x = 123;DBInt y = DBInt.Null;DBInt y = DBInt.Null;DBInt z = x + y;DBInt z = x + y;

Operator OverloadingOperator Overloading Binary and Unary OperatorsBinary and Unary Operators

Binary OperatorsBinary Operators + - * / % & | ^ << >> == != > < >= <=+ - * / % & | ^ << >> == != > < >= <=

Unary OperatorsUnary Operators + - ! ~ ++ --+ - ! ~ ++ --

AgendaAgenda

OverviewOverview Program StructureProgram Structure Value Types and Reference TypesValue Types and Reference Types Base Classes, Derived Classes, Abstract Base Classes, Derived Classes, Abstract

Classes, & InterfacesClasses, & Interfaces Delegates and EventsDelegates and Events Operator OverloadingOperator Overloading VersioningVersioning

Language FeaturesLanguage Features VersioningVersioning

Overlooked in most languagesOverlooked in most languages C++ and Java produce fragile base classes C++ and Java produce fragile base 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 C# can't guarantee versioningC# 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)

class Derived: Baseclass Derived: Base // version 1// version 1{{ public virtual void Foo() {public virtual void Foo() { Console.WriteLine("Derived.Foo"); Console.WriteLine("Derived.Foo"); }}}}

class Derived: Baseclass Derived: Base // version 2a // version 2a{{ new public virtual void Foo() {new public virtual void Foo() { Console.WriteLine("Derived.Foo"); Console.WriteLine("Derived.Foo"); }}}}

class Derived: Baseclass Derived: Base // version 2b// version 2b{{ public override void Foo() {public override void Foo() { base.Foo();base.Foo(); Console.WriteLine("Derived.Foo"); Console.WriteLine("Derived.Foo"); }}}}

class Baseclass Base // version 1// version 1{{}}

class Base class Base // version 2 // version 2 {{ public virtual void Foo() {public virtual void Foo() { Console.WriteLine("Base.Foo"); Console.WriteLine("Base.Foo"); }}}}

Language FeaturesLanguage Features VersioningVersioning

Demonstration 4Demonstration 4

Operator OverloadingOperator OverloadingVersionVersion

MSDN Subscriptions MSDN Subscriptions THE way to get Visual Studio .NETTHE way to get Visual Studio .NET

Visual Studio .NETVisual Studio .NET MSDN SubscriptionsMSDN Subscriptions

NE

WN

EW

ProfessionalProfessional Tools to build applications Tools to build applications

and XML Web services and XML Web services for Windows and the Webfor Windows and the Web

MSDN ProfessionalMSDN Professional$1199 new$1199 new

$899 renewal/upgrade$899 renewal/upgrade

MSDN EnterpriseMSDN Enterprise$2199 new$2199 new

$1599 renewal/upgrade$1599 renewal/upgrade

MSDN UniversalMSDN Universal$2799 new$2799 new

$2299 renewal/upgrade$2299 renewal/upgrade

Enterprise DeveloperEnterprise Developer Enterprise lifecycle toolsEnterprise lifecycle tools Team development supportTeam development support Core .NET Enterprise ServersCore .NET Enterprise Servers

Enterprise ArchitectEnterprise Architect Software and data modelingSoftware and data modeling Enterprise templatesEnterprise templates Architectural guidanceArchitectural guidance

Questions?Questions?