Top Banner
Object Oriented Object Oriented Programming Programming in .NET in .NET Presented by Presented by Greg Sohl Greg Sohl © 2004, Gregory M. Sohl
35

Object Oriented Programming in .NET

Apr 08, 2016

Download

Documents

gregsohl

A presentation I gave in the early 2000's, that still is relevant today. Covers the basic aspects of OOP in .NET, with examples in C#.
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: Object Oriented Programming in .NET

Object Oriented Object Oriented Programming in .NETProgramming in .NET

Presented byPresented byGreg SohlGreg Sohl

© 2004, Gregory M. Sohl

Page 2: Object Oriented Programming in .NET

OverviewOverview

Working with C#, VB.NET and the .NET Working with C#, VB.NET and the .NET Framework requires an understanding of Object Framework requires an understanding of Object Oriented Programming (OOP) techniques.Oriented Programming (OOP) techniques..NET Framework is Object Oriented throughout.NET Framework is Object Oriented throughoutThis presentation will cover the basics of OOPThis presentation will cover the basics of OOP

Page 3: Object Oriented Programming in .NET

AgendaAgenda

Basic OOP ConceptsBasic OOP ConceptsHow OOP is used in .NETHow OOP is used in .NET

Page 4: Object Oriented Programming in .NET

OOP ConceptsOOP Concepts

Objects are things in the problem domainObjects are things in the problem domainAn object-oriented language supports the An object-oriented language supports the development of applications based upon the development of applications based upon the objects in the problem.objects in the problem.

Page 5: Object Oriented Programming in .NET

ClassesClasses

Classes are templates used for defining new Classes are templates used for defining new types – the building blocks for OOPtypes – the building blocks for OOPDescribes both the data and behaviors of Describes both the data and behaviors of objectsobjectsClasses are often referred to as abstractionsClasses are often referred to as abstractionsClasses are not objects – rather they are the Classes are not objects – rather they are the blueprint for creating objects in memoryblueprint for creating objects in memoryObjects are instantiated from a classObjects are instantiated from a class

Page 6: Object Oriented Programming in .NET

Class MembersClass Members

DataData Fields – data associated with the classFields – data associated with the class Properties – like a field but holds no data – executes Properties – like a field but holds no data – executes

get and set methodsget and set methods

BehaviorBehavior Constructors – called when a new instance is being Constructors – called when a new instance is being

created. Typically contains initialization codecreated. Typically contains initialization code Methods – functions to act on the class dataMethods – functions to act on the class data Events – messages sent by objects to event handlers Events – messages sent by objects to event handlers

(delegates) (delegates)

Page 7: Object Oriented Programming in .NET

EncapsulationEncapsulation

OOP uses classes to hide data and offer OOP uses classes to hide data and offer methods to manipulate datamethods to manipulate dataEncapsulation brings data and behavior together Encapsulation brings data and behavior together in an object.in an object.By contrast, functional or procedural By contrast, functional or procedural programming creates data structures and programming creates data structures and functions that manipulate the data structures.functions that manipulate the data structures.Private and Protected access levels combined Private and Protected access levels combined with properties (get / set) or accessor methods with properties (get / set) or accessor methods ensure encapsulationensure encapsulation

Page 8: Object Oriented Programming in .NET

Class Members - AgainClass Members - AgainMembers come in two flavorsMembers come in two flavors

Instance membersInstance members Static members (Shared in VB.NET)Static members (Shared in VB.NET)

Instance members may only be referenced on an Instance members may only be referenced on an instantiated object with the notation instantiated object with the notation object.memberobject.memberStatic members may be called prior to object Static members may be called prior to object instantiation but may not reference any instance instantiation but may not reference any instance members with the notation members with the notation class.memberclass.member. Methods . Methods are sometimes called “Class Methods”are sometimes called “Class Methods”Static members are “shared” by all instances of a classStatic members are “shared” by all instances of a classFramework example: System.Drawing.Image.FromFile Framework example: System.Drawing.Image.FromFile methodmethod

Page 9: Object Oriented Programming in .NET

FieldsFields

Fields are the data contained by a classFields are the data contained by a classAny .NET data typeAny .NET data type

Page 10: Object Oriented Programming in .NET

PropertiesProperties

Properties feel like public fieldsProperties feel like public fieldsHave no actual data associated with themHave no actual data associated with themImplemented with get and set accessor methodsImplemented with get and set accessor methodsCan contain logic to access and set data – great Can contain logic to access and set data – great for validation of set datafor validation of set dataGreat for encapsulation – avoiding writing Great for encapsulation – avoiding writing getThis and setThat methodsgetThis and setThat methods

Page 11: Object Oriented Programming in .NET

MethodsMethods

Sub or Function to declare in VB.NETSub or Function to declare in VB.NETUsed to implement the behavior of a classUsed to implement the behavior of a classMethods are verbsMethods are verbsTypically acts on the class’ fieldsTypically acts on the class’ fieldsLike a “function” in C++ and PascalLike a “function” in C++ and Pascal

Page 12: Object Oriented Programming in .NET

EventsEvents

A message sent to signal an actionA message sent to signal an actionThe object that raises or triggers the event is the The object that raises or triggers the event is the event senderevent senderThe object that captures the event and responds The object that captures the event and responds to it is the event receiverto it is the event receiver

Page 13: Object Oriented Programming in .NET

Method OverloadingMethod Overloading

One method can have multiple argument listsOne method can have multiple argument listsArgument list “signatures” must be differentArgument list “signatures” must be differentExample:Example:

public ArrayList getContacts(int CompanyKey)public ArrayList getContacts(int CompanyKey) public ArrayList getContacts(string LastName)public ArrayList getContacts(string LastName) Public ArrayList getContacts(decimal MinimumRevenue)Public ArrayList getContacts(decimal MinimumRevenue)

Can’t Include:Can’t Include: Public ArrayList getContacts(string FirstName)Public ArrayList getContacts(string FirstName)

Framework example:Framework example: System.Drawing.Font constructorSystem.Drawing.Font constructor

Page 14: Object Oriented Programming in .NET

Constructors and Object Constructors and Object InstantiationInstantiation

The constructor is the class method that The constructor is the class method that describes how a new object is createddescribes how a new object is createdA constructor is called when an object is A constructor is called when an object is instantiated using New (in VB.NET) or new (in instantiated using New (in VB.NET) or new (in C#)C#)An object must be instantiated before its An object must be instantiated before its methods may be called or data referenced methods may be called or data referenced (except for static / Shared members)(except for static / Shared members)

Page 15: Object Oriented Programming in .NET

Methods vs. PropertiesMethods vs. PropertiesUse a property when the member is a logical data Use a property when the member is a logical data member. member. The operation is a conversion, such as The operation is a conversion, such as Object.ToStringObject.ToString. . The operation is expensive enough that you want to The operation is expensive enough that you want to communicate to the user that they should consider communicate to the user that they should consider caching the result. caching the result. Obtaining a property value using the Obtaining a property value using the get get accessor would accessor would have an observable side effect. have an observable side effect. Calling the member twice in succession produces Calling the member twice in succession produces different results. different results. The order of execution is important. Note that a type's The order of execution is important. Note that a type's properties should be able to be set and retrieved in any properties should be able to be set and retrieved in any order. order. The member is static but returns a value that can be The member is static but returns a value that can be changed. changed. The member returns an array. The member returns an array.

Page 16: Object Oriented Programming in .NET

Class Member’s Access LevelsClass Member’s Access Levels

Private – visible only within the classPrivate – visible only within the classProtected – visible to the class and derived Protected – visible to the class and derived classesclassesInternal/Friend – visible only in the same Internal/Friend – visible only in the same assemblyassemblyPublic – visible anywhere outside the classPublic – visible anywhere outside the class

Page 17: Object Oriented Programming in .NET

SolutionProject X

Project Y

Class A Class B

Class C

Class M Class N

private int a;protected int b;internal int c;protected internal int d;public int e; Derived from A

Derived from A

Page 18: Object Oriented Programming in .NET

DemonstrationDemonstrationClass MembersClass Members

Take a look at the various types of Take a look at the various types of class members.class members.

Page 19: Object Oriented Programming in .NET

Object ReferencesObject References

The New (or new) operator returns a reference The New (or new) operator returns a reference to the newly created instance of the class, i.e. to the newly created instance of the class, i.e. the object.the object.A variable that is declared as a class type is A variable that is declared as a class type is called a reference type. These are descendents called a reference type. These are descendents of System.objectof System.objectOther variables are declared as primitives are Other variables are declared as primitives are called value types. These include System.Int32, called value types. These include System.Int32, System.Boolean and descendents of System.Boolean and descendents of System.ValueTypeSystem.ValueType

Page 20: Object Oriented Programming in .NET

DemonstrationDemonstrationValue Types vs. Reference TypesValue Types vs. Reference Types

Compare the behavior of value type Compare the behavior of value type and reference type variables.and reference type variables.

Page 21: Object Oriented Programming in .NET

InheritanceInheritance

Inheritance allows new classes to be created Inheritance allows new classes to be created based upon existing classes.based upon existing classes.Eliminates the need to re-implement common Eliminates the need to re-implement common functionalityfunctionalityThe .NET Framework classes make heavy use The .NET Framework classes make heavy use of inheritance. All classes inherit from of inheritance. All classes inherit from System.Object.System.Object.

Page 22: Object Oriented Programming in .NET

SolutionProject X

Project Y

Class A Class B

Class C

Class M Class N

private int a;protected int b;internal int c;protected internal int d;public int e; Derived from A

Derived from A

Page 23: Object Oriented Programming in .NET

DemonstrationDemonstrationClass InheritanceClass Inheritance

Show how classes can inherit the Show how classes can inherit the members of other classes, creating a members of other classes, creating a base class, child class relationship.base class, child class relationship.

Page 24: Object Oriented Programming in .NET

PolymorphismPolymorphism

Polymorphism makes inheritance come to lifePolymorphism makes inheritance come to lifeAllows treating an instance of a derived class as Allows treating an instance of a derived class as though it is an instance of the base classthough it is an instance of the base classAllows overridden functionality in derived Allows overridden functionality in derived classes to be dynamically called when classes to be dynamically called when referencing the functionality from a base classreferencing the functionality from a base classImplementation is discovered at runtime, not Implementation is discovered at runtime, not compile timecompile time

Page 25: Object Oriented Programming in .NET

DemonstrationDemonstrationPolymorphismPolymorphism

Shows treating derived classes as Shows treating derived classes as base classes and the dynamicity of base classes and the dynamicity of

overridden functionality.overridden functionality.

Page 26: Object Oriented Programming in .NET

Abstract ClassesAbstract Classes

Special type of class that cannot be instantiated. Special type of class that cannot be instantiated. The can only be based classes. Provides The can only be based classes. Provides functionality and data for derived classes.functionality and data for derived classes.Framework example: System.Drawing.ImageFramework example: System.Drawing.Image

Page 27: Object Oriented Programming in .NET

DemonstrationDemonstrationAbstract ClassesAbstract Classes

Showing how an abstract class is Showing how an abstract class is implemented and derived from.implemented and derived from.

Page 28: Object Oriented Programming in .NET

InterfacesInterfaces

An interface is a description of functionality that An interface is a description of functionality that must be implemented in a class. must be implemented in a class. They create a signature of a class – a contractThey create a signature of a class – a contractA class that “implements” an interface must A class that “implements” an interface must implement every member declared in the implement every member declared in the interface.interface.Interfaces are similar to Abstract Classes. They Interfaces are similar to Abstract Classes. They have define methods and properties but contain have define methods and properties but contain no actual functionality.no actual functionality.Framework example: IComparableFramework example: IComparable

Page 29: Object Oriented Programming in .NET

DemonstrationDemonstrationInterfacesInterfaces

Showing how an interface is defined Showing how an interface is defined and implemented by a class.and implemented by a class.

Page 30: Object Oriented Programming in .NET

Inheritance vs. InterfacesInheritance vs. Interfaces

Abstract classes differ from interfaces in that Abstract classes differ from interfaces in that they can contain functionality and data membersthey can contain functionality and data membersA class can inherit only one base class, but can A class can inherit only one base class, but can implement multiple interfacesimplement multiple interfacesUse abstract classes when you want to Use abstract classes when you want to implement some base functionalityimplement some base functionalityUse interfaces to enforce most other contractsUse interfaces to enforce most other contracts

Page 31: Object Oriented Programming in .NET

Lightweight “Objects”Lightweight “Objects”

C# C# structstruct, VB.NET , VB.NET StructureStructureLike an object but allows no inheritanceLike an object but allows no inheritanceTreated like a value type instead of a reference Treated like a value type instead of a reference typetypeUse in an array of structured data instead of an Use in an array of structured data instead of an Object to conserve memory and speed accessObject to conserve memory and speed access

Page 32: Object Oriented Programming in .NET

SummarySummary

The object oriented techniques that you use in The object oriented techniques that you use in your code are shared by the .NET Framework your code are shared by the .NET Framework classes.classes.Effective use of the .NET Framework requires a Effective use of the .NET Framework requires a strong understanding of OOP.strong understanding of OOP.A sometimes difficult mental transition is A sometimes difficult mental transition is required to get from procedural to OOP.required to get from procedural to OOP.Properly applied, OOP can help shorten Properly applied, OOP can help shorten development time and improve maintainabilitydevelopment time and improve maintainability

Page 33: Object Oriented Programming in .NET

ReferencesReferencesMSDN Webcast: MSPress Author Series-OOP MSDN Webcast: MSPress Author Series-OOP with Microsoft Visual Basic .NET and with Microsoft Visual Basic .NET and Microsoft Visual C# .NET Step by StepMicrosoft Visual C# .NET Step by Step http://www.microsoft.com/usa/webcasts/ondemand/http://www.microsoft.com/usa/webcasts/ondemand/

701.asp701.aspMSDN Webcast: Reduce, Reuse, Recycle MSDN Webcast: Reduce, Reuse, Recycle (Session 4)—Object-Oriented Concepts in (Session 4)—Object-Oriented Concepts in Microsoft .NET Winforms ApplicationsMicrosoft .NET Winforms Applications http://msevents.microsoft.com/cui/http://msevents.microsoft.com/cui/

WebCastEventDetails.aspx?WebCastEventDetails.aspx?EventID=1032257713&EventCategory=5&culture=en-EventID=1032257713&EventCategory=5&culture=en-US&CountryCode=USUS&CountryCode=US

Page 34: Object Oriented Programming in .NET

ReferencesReferences

Designing Object-Oriented Programs In C#Designing Object-Oriented Programs In C# http://www.csharphelp.com/archives/archive172.htmlhttp://www.csharphelp.com/archives/archive172.html

Introduction to OOP in VB.NET Introduction to OOP in VB.NET http://www.ondotnet.com/pub/a/dotnet/2002/09/22/vb-http://www.ondotnet.com/pub/a/dotnet/2002/09/22/vb-

oop.htmloop.html

Object-Oriented Programming in Visual BasicObject-Oriented Programming in Visual Basic http://msdn.microsoft.com/library/default.asp?url=/http://msdn.microsoft.com/library/default.asp?url=/

library/en-us/vbcn7/html/library/en-us/vbcn7/html/vbconprogrammingwithobjects.aspvbconprogrammingwithobjects.asp

Page 35: Object Oriented Programming in .NET

Thank You!Thank You!

Questions?Questions?