Apidays New York 2024 - The value of a flexible API Management solution for O...
Object-oriented Programming-with C#
1. Object-OrientedObject-Oriented
Programming with C#Programming with C#
Classes, Constructors, Properties, Events, StaticClasses, Constructors, Properties, Events, Static
Members, Interfaces, Inheritance, PolymorphismMembers, Interfaces, Inheritance, Polymorphism
Doncho MinkovDoncho Minkov
Telerik School AcademyTelerik School Academy
schoolacademy.telerik.comschoolacademy.telerik.com
Technical TrainerTechnical Trainer
http://www.minkov.ithttp://www.minkov.it
2. Table of ContentsTable of Contents
Defining ClassesDefining Classes
Access ModifiersAccess Modifiers
ConstructorsConstructors
Fields, Constants and PropertiesFields, Constants and Properties
Static MembersStatic Members
StructuresStructures
Delegates and EventsDelegates and Events
InterfacesInterfaces
InheritanceInheritance
PolymorphismPolymorphism
3. OOP andOOP and .NET.NET
InIn .NET.NET Framework the object-oriented approachFramework the object-oriented approach
has roots in the deepest architectural levelhas roots in the deepest architectural level
AllAll .NET applications are object-oriented.NET applications are object-oriented
AllAll .NET.NET languages are object-orientedlanguages are object-oriented
The class concept from OOP hasThe class concept from OOP has two realizations:two realizations:
Classes and structuresClasses and structures
There is no multiple inheritance in .NETThere is no multiple inheritance in .NET
Classes can implement several interfaces at theClasses can implement several interfaces at the
same timesame time
5. Classes in OOPClasses in OOP
Classes model real-world objects and defineClasses model real-world objects and define
AttributesAttributes (state, properties, fields)(state, properties, fields)
BehaviorBehavior (methods, operations)(methods, operations)
Classes describe structure of objectsClasses describe structure of objects
Objects describe particular instance of a classObjects describe particular instance of a class
Properties hold information about theProperties hold information about the
modeled object relevant to the problemmodeled object relevant to the problem
Operations implement object behaviorOperations implement object behavior
6. Classes in C#Classes in C#
Classes in C# could have following members:Classes in C# could have following members:
FieldsFields,, constantsconstants,, methodsmethods,, propertiesproperties,,
indexersindexers,, eventsevents,, operatorsoperators,, constructorsconstructors,,
destructorsdestructors
Inner typesInner types ((inner classesinner classes,, structuresstructures,,
interfacesinterfaces,, delegatesdelegates, ...), ...)
Members can have access modifiers (scope)Members can have access modifiers (scope)
publicpublic,, privateprivate,, protectedprotected,, internalinternal
Members can beMembers can be
staticstatic ((commoncommon)) or specific for a given objector specific for a given object
6
7. Simple Class DefinitionSimple Class Definition
public class Cat : Animalpublic class Cat : Animal
{{
private string name;private string name;
private string owner;private string owner;
public Cat(string name, string owner)public Cat(string name, string owner)
{{
this.name = name;this.name = name;
this.owner = owner;this.owner = owner;
}}
public string Namepublic string Name
{{
get { return name; }get { return name; }
set { name = value; }set { name = value; }
}}
FieldsFields
ConstructorConstructor
PropertyProperty
Begin of class definitionBegin of class definition
Inherited (base)Inherited (base)
classclass
8. Simple Class Definition (2)Simple Class Definition (2)
public string Ownerpublic string Owner
{{
get { return owner;}get { return owner;}
set { owner = value; }set { owner = value; }
}}
public void SayMiau()public void SayMiau()
{{
Console.WriteLine("Miauuuuuuu!");Console.WriteLine("Miauuuuuuu!");
}}
}}
MethodMethod
End ofEnd of
classclass
definitiondefinition
9. Class Definition and MembersClass Definition and Members
Class definition consists of:Class definition consists of:
Class declarationClass declaration
Inherited class or implemented interfacesInherited class or implemented interfaces
Fields (static or not)Fields (static or not)
Constructors (static or not)Constructors (static or not)
Properties (static or not)Properties (static or not)
Methods (static or not)Methods (static or not)
Events, inner types, etc.Events, inner types, etc.
11. Access ModifiersAccess Modifiers
Class members can have access modifiersClass members can have access modifiers
Used to restrict the classes able to access themUsed to restrict the classes able to access them
Supports the OOP principle "Supports the OOP principle "encapsulationencapsulation""
Class members can be:Class members can be:
publicpublic – accessible from any class– accessible from any class
protectedprotected – accessible from the class itself and– accessible from the class itself and
all its descendent classesall its descendent classes
privateprivate – accessible from the class itself only– accessible from the class itself only
internalinternal – accessible from the current– accessible from the current
assembly (used by default)assembly (used by default)
13. Task: Define ClassTask: Define Class DogDog
Our task is to define a simple class thatOur task is to define a simple class that
represents information about a dogrepresents information about a dog
The dog should have name and breedThe dog should have name and breed
If there is no name or breed assignedIf there is no name or breed assigned
to the dog, it should be named "Balkan"to the dog, it should be named "Balkan"
and its breed should be "Street excellent"and its breed should be "Street excellent"
It should be able to view and change the nameIt should be able to view and change the name
and the breed of the dogand the breed of the dog
The dog should be able to barkThe dog should be able to bark
14. Defining ClassDefining Class DogDog – Example– Example
public class Dogpublic class Dog
{{
private string name;private string name;
private string breed;private string breed;
public Dog()public Dog()
{{
this.name = "Balkan";this.name = "Balkan";
this.breed = "Street excellent";this.breed = "Street excellent";
}}
public Dog(string name, string breed)public Dog(string name, string breed)
{{
this.name = name;this.name = name;
this.breed = breed;this.breed = breed;
}}
////(example(example
continues)continues)
15. Defining ClassDefining Class DogDog – Example (2)– Example (2)
public string Namepublic string Name
{{
get { return name; }get { return name; }
set { name = value; }set { name = value; }
}}
public string Breedpublic string Breed
{{
get { return breed; }get { return breed; }
set { breed = value; }set { breed = value; }
}}
public void SayBau()public void SayBau()
{{
Console.WriteLine("{0} said: Bauuuuuu!",Console.WriteLine("{0} said: Bauuuuuu!",
name);name);
}}
}}
17. Using ClassesUsing Classes
How to use classes?How to use classes?
Create a new instanceCreate a new instance
Access the properties of the classAccess the properties of the class
Invoke methodsInvoke methods
Handle eventsHandle events
How to define classes?How to define classes?
Create new class and define its membersCreate new class and define its members
Create new class using some other as base classCreate new class using some other as base class
18. How to Use Classes (Non-static)?How to Use Classes (Non-static)?
Create an instanceCreate an instance
Initialize fieldsInitialize fields
Manipulate instanceManipulate instance
Read / change propertiesRead / change properties
Invoke methodsInvoke methods
Handle eventsHandle events
Release occupied resourcesRelease occupied resources
Done automatically in most casesDone automatically in most cases
19. Task: Dog MeetingTask: Dog Meeting
Our task is as follows:Our task is as follows:
Create 3 dogsCreate 3 dogs
First should be named “Sharo”,First should be named “Sharo”, second – “Rex”second – “Rex”
and the last – left without nameand the last – left without name
Add all dogs in an arrayAdd all dogs in an array
Iterate through the array elements and askIterate through the array elements and ask
each dog to barkeach dog to bark
Note:Note:
Use theUse the DogDog class from the previous example!class from the previous example!
20. Dog Meeting – ExampleDog Meeting – Example
static void Main()static void Main()
{{
Console.WriteLine("Enter first dog's name: ");Console.WriteLine("Enter first dog's name: ");
dogName = Console.ReadLine();dogName = Console.ReadLine();
Console.WriteLine("Enter first dog's breed: ");Console.WriteLine("Enter first dog's breed: ");
dogBreed = Console.ReadLine();dogBreed = Console.ReadLine();
// Using the Dog constructor to set name and breed// Using the Dog constructor to set name and breed
Dog firstDog = new Dog(dogName, dogBreed);Dog firstDog = new Dog(dogName, dogBreed);
Dog secondDog = new Dog();Dog secondDog = new Dog();
Console.WriteLine("Enter second dog's name: ");Console.WriteLine("Enter second dog's name: ");
dogName = Console.ReadLine();dogName = Console.ReadLine();
Console.WriteLine("Enter second dog's breed: ");Console.WriteLine("Enter second dog's breed: ");
dogBreed = Console.ReadLine();dogBreed = Console.ReadLine();
// Using properties to set name and breed// Using properties to set name and breed
secondDog.Name = dogName;secondDog.Name = dogName;
secondDog.Breed = dogBreed;secondDog.Breed = dogBreed;
}}
22. What is Constructor?What is Constructor?
Constructors are special methodsConstructors are special methods
Invoked when creating a new instance of anInvoked when creating a new instance of an
objectobject
Used to initialize the fields of the instanceUsed to initialize the fields of the instance
Constructors has the same name as the classConstructors has the same name as the class
Have no return typeHave no return type
Can have parametersCan have parameters
Can beCan be privateprivate,, protectedprotected,, internalinternal,,
publicpublic
23. Defining ConstructorsDefining Constructors
public class Pointpublic class Point
{{
private int xCoord;private int xCoord;
private int yCoord;private int yCoord;
// Simple default constructor// Simple default constructor
public Point()public Point()
{{
xCoord = 0;xCoord = 0;
yCoord = 0;yCoord = 0;
}}
// More code ...// More code ...
}}
ClassClass PointPoint with parameterless constructor:with parameterless constructor:
24. Defining Constructors (2)Defining Constructors (2)
public class Personpublic class Person
{{
private string name;private string name;
private int age;private int age;
// Default constructor// Default constructor
public Person()public Person()
{{
name = "[no name]";name = "[no name]";
age = 0;age = 0;
}}
// Constructor with parameters// Constructor with parameters
public Person(string name, int age)public Person(string name, int age)
{{
this.name = name;this.name = name;
this.age = age;this.age = age;
}}
// More code ...// More code ...
}}
As ruleAs rule
constructors shouldconstructors should
initialize all owninitialize all own
class fields.class fields.
25. Constructors and InitializationConstructors and Initialization
Pay attention when using inline initialization!Pay attention when using inline initialization!
public class ClockAlarmpublic class ClockAlarm
{{
private int hours = 9; // Inline initializationprivate int hours = 9; // Inline initialization
private int minutes = 0; // Inline initializationprivate int minutes = 0; // Inline initialization
// Default constructor// Default constructor
public ClockAlarm()public ClockAlarm()
{ }{ }
// Constructor with parameters// Constructor with parameters
public ClockAlarm(int hours, int minutes)public ClockAlarm(int hours, int minutes)
{{
this.hours = hours; // Invoked after thethis.hours = hours; // Invoked after the
inlineinline
this.minutes = minutes; // initialization!this.minutes = minutes; // initialization!
}}
// More code ...// More code ...
}}
26. Chaining Constructors CallsChaining Constructors Calls
Reusing constructorsReusing constructors
public class Pointpublic class Point
{{
private int xCoord;private int xCoord;
private int yCoord;private int yCoord;
public Point() : this(0,0) // Reuse constructorpublic Point() : this(0,0) // Reuse constructor
{{
}}
public Point(int xCoord, int yCoord)public Point(int xCoord, int yCoord)
{{
this.xCoord = xCoord;this.xCoord = xCoord;
this.yCoord = yCoord;this.yCoord = yCoord;
}}
// More code ...// More code ...
}}
28. FieldsFields
FieldsFields contain data for the class instancecontain data for the class instance
Can be arbitrary typeCan be arbitrary type
Have given scopeHave given scope
Can be declared with a specific valueCan be declared with a specific value
class Studentclass Student
{{
private string firstName;private string firstName;
private string lastName;private string lastName;
private int course = 1;private int course = 1;
private string speciality;private string speciality;
protected Course[] coursesTaken;protected Course[] coursesTaken;
private string remarks = "(no remarks)";private string remarks = "(no remarks)";
}}
29. ConstantsConstants
Constant fields are defined like fields, but:Constant fields are defined like fields, but:
Defined withDefined with constconst
Must be initialized at their definitionMust be initialized at their definition
Their value can not be changed at runtimeTheir value can not be changed at runtime
public class MathConstantspublic class MathConstants
{{
public const string PI_SYMBOL = "π";public const string PI_SYMBOL = "π";
public const double PI = 3.1415926535897932385;public const double PI = 3.1415926535897932385;
public const double E = 2.7182818284590452354;public const double E = 2.7182818284590452354;
public const double LN10 = 2.30258509299405;public const double LN10 = 2.30258509299405;
public const double LN2 = 0.693147180559945;public const double LN2 = 0.693147180559945;
}}
30. Read-Only FieldsRead-Only Fields
Initialized at the definition or in the constructorInitialized at the definition or in the constructor
Can not be modified furtherCan not be modified further
Defined with the keywordDefined with the keyword readonlyreadonly
RepresentRepresent runtime constantsruntime constants
public class ReadOnlyDemopublic class ReadOnlyDemo
{{
private readonly int size;private readonly int size;
public ReadOnlyDemo(int Size)public ReadOnlyDemo(int Size)
{{
size = Size; // can not be further modified!size = Size; // can not be further modified!
}}
}}
31. The Role of PropertiesThe Role of Properties
Expose object's data to the outside worldExpose object's data to the outside world
Control how the data is manipulatedControl how the data is manipulated
Properties can be:Properties can be:
Read-onlyRead-only
Write-onlyWrite-only
Read and writeRead and write
Give good level of abstractionGive good level of abstraction
Make writing code easierMake writing code easier
32. Defining Properties in C#Defining Properties in C#
Properties should have:Properties should have:
Access modifier (Access modifier (publicpublic,, protectedprotected, etc.), etc.)
Return typeReturn type
Unique nameUnique name
GetGet and / orand / or SetSet partpart
Can contain code processing data in specificCan contain code processing data in specific
wayway
33. Defining Properties – ExampleDefining Properties – Example
public class Pointpublic class Point
{{
private int xCoord;private int xCoord;
private int yCoord;private int yCoord;
public int XCoordpublic int XCoord
{{
get { return xCoord; }get { return xCoord; }
set { xCoord = value; }set { xCoord = value; }
}}
public int YCoordpublic int YCoord
{{
get { return yCoord; }get { return yCoord; }
set { yCoord = value; }set { yCoord = value; }
}}
// More code ...// More code ...
}}
34. Dynamic PropertiesDynamic Properties
Properties are not obligatory bound to a classProperties are not obligatory bound to a class
field – can be calculated dynamically:field – can be calculated dynamically:
public class Rectanglepublic class Rectangle
{{
private float width;private float width;
private float height;private float height;
// More code ...// More code ...
public float Areapublic float Area
{{
getget
{{
return width * height;return width * height;
}}
}}
}}
35. Automatic PropertiesAutomatic Properties
Properties could be defined without anProperties could be defined without an
underlying field behind themunderlying field behind them
It is automatically created by the C# compilerIt is automatically created by the C# compiler
35
class UserProfileclass UserProfile
{{
public int UserId { get; set; }public int UserId { get; set; }
public string FirstName { get; set; }public string FirstName { get; set; }
public string LastName { get; set; }public string LastName { get; set; }
}}
……
UserProfile profile = new UserProfile() {UserProfile profile = new UserProfile() {
FirstName = "Steve",FirstName = "Steve",
LastName = "Balmer",LastName = "Balmer",
UserId = 91112 };UserId = 91112 };
37. Static MembersStatic Members
Static members are associated with a typeStatic members are associated with a type
rather than with an instancerather than with an instance
Defined with the modifierDefined with the modifier staticstatic
Static can be used forStatic can be used for
FieldsFields
PropertiesProperties
MethodsMethods
EventsEvents
ConstructorsConstructors
38. Static vs. Non-StaticStatic vs. Non-Static
StaticStatic::
Associated with a type, not with an instanceAssociated with a type, not with an instance
Non-StaticNon-Static::
The opposite, associated with an instanceThe opposite, associated with an instance
StaticStatic::
Initialized just before the type is used for theInitialized just before the type is used for the
first timefirst time
Non-StaticNon-Static::
Initialized when the constructor is calledInitialized when the constructor is called
39. Static Members – ExampleStatic Members – Example
public class SqrtPrecalculatedpublic class SqrtPrecalculated
{{
public const int MAX_VALUE = 10000;public const int MAX_VALUE = 10000;
// Static field// Static field
private static int[] sqrtValues;private static int[] sqrtValues;
// Static constructor// Static constructor
private static SqrtPrecalculated()private static SqrtPrecalculated()
{{
sqrtValues = new int[MAX_VALUE + 1];sqrtValues = new int[MAX_VALUE + 1];
for (int i = 0; i < sqrtValues.Length; i++)for (int i = 0; i < sqrtValues.Length; i++)
{{
sqrtValues[i] = (int)Math.Sqrt(i);sqrtValues[i] = (int)Math.Sqrt(i);
}}
}}
////(example continues)(example continues)
40. Static Members – Example (2)Static Members – Example (2)
// Static method// Static method
public static int GetSqrt(int value)public static int GetSqrt(int value)
{{
return sqrtValues[value];return sqrtValues[value];
}}
// The Main() method is always static// The Main() method is always static
static void Main()static void Main()
{{
Console.WriteLine(GetSqrt(254));Console.WriteLine(GetSqrt(254));
}}
}}
42. StructuresStructures
Structures represent a combination of fieldsStructures represent a combination of fields
with datawith data
Look like the classes, but are value typesLook like the classes, but are value types
Their content is stored in the stackTheir content is stored in the stack
Transmitted by valueTransmitted by value
Destroyed when go out of scopeDestroyed when go out of scope
However classes are reference type and areHowever classes are reference type and are
placed in the dynamic memory (heap)placed in the dynamic memory (heap)
Their creation and destruction is slowerTheir creation and destruction is slower
43. StructuresStructures –– ExampleExample
struct Pointstruct Point
{{
public int X, Y;public int X, Y;
}}
struct Colorstruct Color
{{
public byte redValue;public byte redValue;
public byte greenValue;public byte greenValue;
public byte blueValue;public byte blueValue;
}}
struct Squarestruct Square
{{
public Point location;public Point location;
public int size;public int size;
public Color borderColor;public Color borderColor;
public Color surfaceColor;public Color surfaceColor;
}}
44. When to Use Structures?When to Use Structures?
Use structuresUse structures
To make your type behave as a primitive typeTo make your type behave as a primitive type
If you create many instances and after that youIf you create many instances and after that you
free themfree them –– e.g. in a cyclee.g. in a cycle
Do not use structuresDo not use structures
When you often transmit your instances asWhen you often transmit your instances as
method parametersmethod parameters
If you use collections without genericsIf you use collections without generics ((tootoo
much boxingmuch boxing // unboxing!)unboxing!)
46. What are Delegates?What are Delegates?
Delegates are reference typesDelegates are reference types
Describe the signature of a given methodDescribe the signature of a given method
Number and types of the parametersNumber and types of the parameters
The return typeThe return type
Their "values" are methodsTheir "values" are methods
These methods correspond to the signature ofThese methods correspond to the signature of
the delegatethe delegate
47. What are Delegates? (2)What are Delegates? (2)
Delegates are roughly similar to functionDelegates are roughly similar to function
pointers inpointers in CC andand C++C++
Contain a strongly-typed pointer (reference) toContain a strongly-typed pointer (reference) to
a methoda method
They can point to both static or instanceThey can point to both static or instance
methodsmethods
Used to perform callbacksUsed to perform callbacks
48. Delegates – ExampleDelegates – Example
// Declaration of a delegate// Declaration of a delegate
public delegate void SimpleDelegate(string param);public delegate void SimpleDelegate(string param);
public class TestDelegatepublic class TestDelegate
{{
public static void TestFunction(string param)public static void TestFunction(string param)
{{
Console.WriteLine("I was called by a delegate.");Console.WriteLine("I was called by a delegate.");
Console.WriteLine("I got parameter {0}.", param);Console.WriteLine("I got parameter {0}.", param);
}}
public static void Main()public static void Main()
{{
// Instantiation of а delegate// Instantiation of а delegate
SimpleDelegate simpleDelegate =SimpleDelegate simpleDelegate =
new SimpleDelegate(TestFunction);new SimpleDelegate(TestFunction);
// Invocation of the method, pointed by a// Invocation of the method, pointed by a
delegatedelegate
simpleDelegate("test");simpleDelegate("test");
}}
}}
49. Anonymous MethodsAnonymous Methods
We are sometimes forced to create a class or aWe are sometimes forced to create a class or a
method just for the sake of using a delegatemethod just for the sake of using a delegate
The code involved is often relativelyThe code involved is often relatively
short and simpleshort and simple
Anonymous methodsAnonymous methods let you define anlet you define an
nameless method called by a delegatenameless method called by a delegate
Less codingLess coding
Improved code readabilityImproved code readability
50. Using Delegates: Standard WayUsing Delegates: Standard Way
class SomeClassclass SomeClass
{{
delegate void SomeDelegate(string str);delegate void SomeDelegate(string str);
public void InvokeMethod()public void InvokeMethod()
{{
SomeDelegate dlg = newSomeDelegate dlg = new
SomeDelegate(SomeMethod);SomeDelegate(SomeMethod);
dlg("Hello");dlg("Hello");
}}
void SomeMethod(string str)void SomeMethod(string str)
{{
Console.WriteLine(str);Console.WriteLine(str);
}}
}}
51. Using Anonymous MethodsUsing Anonymous Methods
The same thing can be accomplished byThe same thing can be accomplished by
using an anonymous method:using an anonymous method:
class SomeClassclass SomeClass
{{
delegate void SomeDelegate(string str);delegate void SomeDelegate(string str);
public void InvokeMethod()public void InvokeMethod()
{{
SomeDelegate dlg = delegate(string str)SomeDelegate dlg = delegate(string str)
{{
Console.WriteLine(str);Console.WriteLine(str);
};};
dlg("Hello");dlg("Hello");
}}
}}
52. EventsEvents
In component-oriented programming theIn component-oriented programming the
components send events to their owner to notifycomponents send events to their owner to notify
them when something happensthem when something happens
E.g. when a button is pressed an event is raisedE.g. when a button is pressed an event is raised
The object which causes an event is calledThe object which causes an event is called eventevent
sendersender
The object which receives an event is calledThe object which receives an event is called
event receiverevent receiver
In order to be able to receive an event the eventIn order to be able to receive an event the event
receivers must firstreceivers must first ""subscribe for the eventsubscribe for the event""
53. Events inEvents in .NET.NET
In the component model ofIn the component model of .NET Framework.NET Framework
delegates and events provide mechanism for:delegates and events provide mechanism for:
SubscriptionSubscription to an eventto an event
Sending an eventSending an event
Receiving an eventReceiving an event
Events in C#Events in C# are special instances of delegatesare special instances of delegates
declared by the C# keyworddeclared by the C# keyword eventevent
Example (Example (Button.ClickButton.Click):):
public event EventHandler Click;public event EventHandler Click;
54. Events inEvents in .NET (2).NET (2)
The C# compiler automatically defines theThe C# compiler automatically defines the +=+=
andand -=-= operators for eventsoperators for events
+=+= subscribe for an eventsubscribe for an event
-=-= unsubscribe for an eventunsubscribe for an event
There are no other allowed operationsThere are no other allowed operations
Example:Example:
Button button = new Button("OK");Button button = new Button("OK");
button.Click += delegatebutton.Click += delegate
{{
Console.WriteLine("Button clicked.");Console.WriteLine("Button clicked.");
};};
55. Events vs. DelegatesEvents vs. Delegates
EventsEvents are not the same asare not the same as member fields ofmember fields of
type delegatetype delegate
The event is processed by a delegateThe event is processed by a delegate
Events can be members of an interface unlikeEvents can be members of an interface unlike
delegatesdelegates
Calling of an event can only be doneCalling of an event can only be done in thein the
class it is defined inclass it is defined in
By default the access to the events isBy default the access to the events is
synchronized (thread-safe)synchronized (thread-safe)
public MyDelegate m;public MyDelegate m; public event MyDelegate m;public event MyDelegate m;≠
56. System.EventHandlerSystem.EventHandler DelegateDelegate
Defines a referenceDefines a reference to ato a callbackcallback methodmethod,,
whichwhich handles eventshandles events
No additional information is sentNo additional information is sent
Used in many occasions internally inUsed in many occasions internally in .NET.NET
E.g. in ASP.NET and Windows FormsE.g. in ASP.NET and Windows Forms
TheThe EventArgsEventArgs class is base class with noclass is base class with no
information about the eventinformation about the event
Sometimes delegates derive from itSometimes delegates derive from it
public delegate void EventHandler(public delegate void EventHandler(
Object sender, EventArgs e);Object sender, EventArgs e);
57. EventHandlerEventHandler – Example– Example
public class Buttonpublic class Button
{{
public event EventHandler Click;public event EventHandler Click;
public event EventHandler GotFocus;public event EventHandler GotFocus;
public event EventHandler TextChanged;public event EventHandler TextChanged;
......
}}
public class ButtonTestpublic class ButtonTest
{{
private static void Button_Click(object sender,private static void Button_Click(object sender,
EventArgs eventArgs)EventArgs eventArgs)
{{
Console.WriteLine("Call Button_Click() event");Console.WriteLine("Call Button_Click() event");
}}
public static void Main()public static void Main()
{{
Button button = new Button();Button button = new Button();
button.Click += Button_Click;button.Click += Button_Click;
}}
}}
59. InterfacesInterfaces
Describe a group ofDescribe a group of methodsmethods (operations),(operations),
propertiesproperties andand eventsevents
Can be implemented by givenCan be implemented by given classclass oror
structurestructure
Define only the methods’ prototypesDefine only the methods’ prototypes
No concrete implementationNo concrete implementation
Can be used to defineCan be used to define abstractabstract data typesdata types
Can not be instantiatedCan not be instantiated
Members do not have scope modifierMembers do not have scope modifier
and by default the scope isand by default the scope is publicpublic
60. Interfaces – ExampleInterfaces – Example
public interface IPersonpublic interface IPerson
{{
string Name // property Namestring Name // property Name
{ get; set; }{ get; set; }
DateTime DateOfBirth // property DateOfBirthDateTime DateOfBirth // property DateOfBirth
{ get; set; }{ get; set; }
int Age // property Age (read-only)int Age // property Age (read-only)
{ get; }{ get; }
}}
61. Interfaces – Example (2)Interfaces – Example (2)
interface IShapeinterface IShape
{{
void SetPosition(int x, int y);void SetPosition(int x, int y);
int CalculateSurface();int CalculateSurface();
}}
interface IMovableinterface IMovable
{{
void Move(int deltaX, int deltaY);void Move(int deltaX, int deltaY);
}}
interface IResizableinterface IResizable
{{
void Resize(int weight);void Resize(int weight);
void Resize(int weightX, int weightY);void Resize(int weightX, int weightY);
void ResizeByX(int weightX);void ResizeByX(int weightX);
void ResizeByY(int weightY);void ResizeByY(int weightY);
}}
62. Interface ImplementationInterface Implementation
Classes and structures can implementClasses and structures can implement
(support) one or many interfaces(support) one or many interfaces
Interface realization must implement all itsInterface realization must implement all its
methodsmethods
If some methods do not have implementationIf some methods do not have implementation
thethe classclass oror structurestructure have to be declaredhave to be declared
as anas an abstractabstract
63. Interface ImplementationInterface Implementation ––
ExampleExample
class Rectangle : IShape, IMovableclass Rectangle : IShape, IMovable
{{
private int x, y, width, height;private int x, y, width, height;
public void SetPosition(int x, int y) // IShapepublic void SetPosition(int x, int y) // IShape
{{
this.x = x;this.x = x;
this.y = y;this.y = y;
}}
public int CalculateSurface() // IShapepublic int CalculateSurface() // IShape
{{
return this.width * this.height;return this.width * this.height;
}}
public void Move(int deltaX, int deltaY) // IMovablepublic void Move(int deltaX, int deltaY) // IMovable
{{
this.x += deltaX;this.x += deltaX;
this.y += deltaY;this.y += deltaY;
}}
}}
64. Abstract ClassesAbstract Classes
Abstract methodAbstract method is a method withoutis a method without
implementationimplementation
Left empty to be implemented by descendantLeft empty to be implemented by descendant
classesclasses
When a class contains at least one abstractWhen a class contains at least one abstract
method, it is calledmethod, it is called abstract classabstract class
Mix between class and interfaceMix between class and interface
Inheritors are obligated toInheritors are obligated to
implement their abstract methodsimplement their abstract methods
Can not be directly instantiatedCan not be directly instantiated
65. Abstract ClassAbstract Class –– ExampleExample
abstract class MovableShape : IShape, IMovableabstract class MovableShape : IShape, IMovable
{{
private int x, y;private int x, y;
public void Move(int deltaX, int deltaY)public void Move(int deltaX, int deltaY)
{{
this.x += deltaX;this.x += deltaX;
this.y += deltaY;this.y += deltaY;
}}
public void SetPosition(int x, int y)public void SetPosition(int x, int y)
{{
this.x = x;this.x = x;
this.y = y;this.y = y;
}}
public abstract int CalculateSurface();public abstract int CalculateSurface();
}}
67. CohesionCohesion
CohesionCohesion describes how closely all thedescribes how closely all the
routines in a class or all the code in a routineroutines in a class or all the code in a routine
support a central purposesupport a central purpose
Cohesion must be strongCohesion must be strong
Classes must contain strongly relatedClasses must contain strongly related
functionality and aim for single purposefunctionality and aim for single purpose
Cohesion is a useful tool for managingCohesion is a useful tool for managing
complexitycomplexity
WWell-defined abstractionsell-defined abstractions keep cohesion strongkeep cohesion strong
68. Good and Bad CohesionGood and Bad Cohesion
Good cohesion: hard disk, CD-ROM, floppyGood cohesion: hard disk, CD-ROM, floppy
BAD: spaghetti codeBAD: spaghetti code
70. Bad CohesionBad Cohesion
Example of bad cohesionExample of bad cohesion
ClassClass MagicMagic that has all these methods:that has all these methods:
Another example:Another example:
MagicClass.MakePizza("Fat Pepperoni");MagicClass.MakePizza("Fat Pepperoni");
MagicClass.WithdrawMoney("999e6");MagicClass.WithdrawMoney("999e6");
MagicClass.OpenDBConnection();MagicClass.OpenDBConnection();
public void PrintDocument(Document d);public void PrintDocument(Document d);
public void SendEmail(string recipient, stringpublic void SendEmail(string recipient, string
subject, string text);subject, string text);
public void CalculateDistanceBetweenPoints(int x1,public void CalculateDistanceBetweenPoints(int x1,
int y1, int x2, int y2)int y1, int x2, int y2)
71. CouplingCoupling
CouplingCoupling describes how tightly a class ordescribes how tightly a class or
routine is related to other classes orroutine is related to other classes or routinesroutines
Coupling must be kept looseCoupling must be kept loose
Modules must depend little on each otherModules must depend little on each other
All classes and routines must have small, direct,All classes and routines must have small, direct,
visible, and flexible relations to other classesvisible, and flexible relations to other classes
and routinesand routines
One module must be easily used by otherOne module must be easily used by other
modulesmodules
72. Loose and Tight CouplingLoose and Tight Coupling
Loose Coupling:Loose Coupling:
Easily replace old HDDEasily replace old HDD
Easily place this HDD toEasily place this HDD to
another motherboardanother motherboard
Tight Coupling:Tight Coupling:
Where is the videoWhere is the video
adapter?adapter?
Can you change the videoCan you change the video
controller?controller?
73. Loose Coupling – ExampleLoose Coupling – Example
class Reportclass Report
{{
public bool LoadFromFile(string fileName) {…}public bool LoadFromFile(string fileName) {…}
public bool SaveToFile(string fileName) {…}public bool SaveToFile(string fileName) {…}
}}
class Printerclass Printer
{{
public static int Print(Report report) {…}public static int Print(Report report) {…}
}}
class LooseCouplingExampleclass LooseCouplingExample
{{
static void Main()static void Main()
{{
Report myReport = new Report();Report myReport = new Report();
myReport.LoadFromFile("C:DailyReport.rep");myReport.LoadFromFile("C:DailyReport.rep");
Printer.Print(myReport);Printer.Print(myReport);
}}
}}
74. Tight Coupling – ExampleTight Coupling – Example
class MathParamsclass MathParams
{{
public static double operand;public static double operand;
public static double result;public static double result;
}}
class MathUtilclass MathUtil
{{
public static void Sqrt()public static void Sqrt()
{{
MathParams.result =MathParams.result =
CalcSqrt(MathParams.operand);CalcSqrt(MathParams.operand);
}}
}}
class Exampleclass Example
{{
static void Main()static void Main()
{{
MathParams.operand = 64;MathParams.operand = 64;
MathUtil.Sqrt();MathUtil.Sqrt();
Console.WriteLine(MathParams.result);Console.WriteLine(MathParams.result);
}}
}}
75. Spaghetti CodeSpaghetti Code
Combination of bad cohesion and tightCombination of bad cohesion and tight
couplingcoupling
class Reportclass Report
{{
public void Print() {…}public void Print() {…}
public void InitPrinter() {…}public void InitPrinter() {…}
public void LoadPrinterDriver(string fileName) {…}public void LoadPrinterDriver(string fileName) {…}
public bool SaveReport(string fileName) {…}public bool SaveReport(string fileName) {…}
public void SetPrinter(string printer) {…}public void SetPrinter(string printer) {…}
}}
class Printerclass Printer
{{
public void SetFileName() {…}public void SetFileName() {…}
public static bool LoadReport() {…}public static bool LoadReport() {…}
public static bool CheckReport() {…}public static bool CheckReport() {…}
}}
77. InheritanceInheritance
InheritanceInheritance is the ability of a class to implicitlyis the ability of a class to implicitly
gain all members from another classgain all members from another class
Inheritance is fundamental concept in OOPInheritance is fundamental concept in OOP
The class whose methods are inherited isThe class whose methods are inherited is
calledcalled basebase (parent) class(parent) class
The class that gains newThe class that gains new functionalityfunctionality is calledis called
derivedderived (child) class(child) class
InheritanceInheritance establishes anestablishes an is-ais-a relationshiprelationship
between classes: A is Bbetween classes: A is B
78. Inheritance (2)Inheritance (2)
All class members are inheritedAll class members are inherited
FieldsFields,, methodsmethods,, propertiesproperties, …, …
InIn C#C# classes could be inheritedclasses could be inherited
The structures in C#The structures in C# could not be inheritedcould not be inherited
Inheritance allows creating deep inheritanceInheritance allows creating deep inheritance
hierarchieshierarchies
InIn ..NET there is no multiple inheritance,NET there is no multiple inheritance,
except when implementing interfacesexcept when implementing interfaces
79. How to DefineHow to Define InheritanceInheritance??
We must specify the name of the base classWe must specify the name of the base class
after the name of the derivedafter the name of the derived
In the constructor of the derived class we useIn the constructor of the derived class we use
the keywordthe keyword basebase to invoke the constructor ofto invoke the constructor of
the base classthe base class
public class Shapepublic class Shape
{...}{...}
public class Circle : Shapepublic class Circle : Shape
{...}{...}
public Circle (int x, int y) : base(x)public Circle (int x, int y) : base(x)
{...}{...}
80. InheritanceInheritance –– ExampleExample
public class Mammalpublic class Mammal
{{
private int age;private int age;
public Mammal(int age)public Mammal(int age)
{{
this.age = age;this.age = age;
}}
public int Agepublic int Age
{{
get { return age; }get { return age; }
set { age = value; }set { age = value; }
}}
public void Sleep()public void Sleep()
{{
Console.WriteLine("Shhh! I'm sleeping!");Console.WriteLine("Shhh! I'm sleeping!");
}}
}}
81. InheritanceInheritance –– ExampleExample (2)(2)
public class Dog : Mammalpublic class Dog : Mammal
{{
private string breed;private string breed;
public Dog(int age, string breed): base(age)public Dog(int age, string breed): base(age)
{{
this.breed = breed;this.breed = breed;
}}
public string Breedpublic string Breed
{{
get { return breed; }get { return breed; }
set { breed = value; }set { breed = value; }
}}
public void WagTail()public void WagTail()
{{
Console.WriteLine("Tail wagging...");Console.WriteLine("Tail wagging...");
}}
}}
82. InheritanceInheritance –– ExampleExample (3)(3)
static void Main()static void Main()
{{
// Create 5 years old mammal// Create 5 years old mammal
Mamal mamal = new Mamal(5);Mamal mamal = new Mamal(5);
Console.WriteLine(mamal.Age);Console.WriteLine(mamal.Age);
mamal.Sleep();mamal.Sleep();
// Create a bulldog, 3 years old// Create a bulldog, 3 years old
Dog dog = new Dog("Bulldog", 3);Dog dog = new Dog("Bulldog", 3);
dog.Sleep();dog.Sleep();
dog.Age = 4;dog.Age = 4;
Console.WriteLine("Age: {0}", dog.Age);Console.WriteLine("Age: {0}", dog.Age);
Console.WriteLine("Breed: {0}", dog.Breed);Console.WriteLine("Breed: {0}", dog.Breed);
dog.WagTail();dog.WagTail();
}}
84. PolymorphismPolymorphism
PolymorphismPolymorphism is fundamental concept inis fundamental concept in
OOPOOP
The ability to handle the objects of a specificThe ability to handle the objects of a specific
class as instances of its parent class and to callclass as instances of its parent class and to call
abstract functionalityabstract functionality
Polymorphism allows creating hierarchiesPolymorphism allows creating hierarchies
with more valuable logical structurewith more valuable logical structure
Allows invoking abstract functionality withoutAllows invoking abstract functionality without
caring how and where it is implementedcaring how and where it is implemented
85. Polymorphism (2)Polymorphism (2)
PolymorphismPolymorphism is usuallyis usually implementedimplemented
through:through:
Virtual methods (Virtual methods (virtualvirtual))
Abstract methodsAbstract methods ((abstractabstract))
Methods from an interfaceMethods from an interface ((interfaceinterface))
InIn C# to override virtual method the keywordC# to override virtual method the keyword
overrideoverride is usedis used
C#C# allows hiding virtual methods in derivedallows hiding virtual methods in derived
classes by the keywordclasses by the keyword newnew
86. PolymorphismPolymorphism –– ExampleExample
class Personclass Person
{{
public virtual void PrintName()public virtual void PrintName()
{{
Console.WriteLine("I am a person.");Console.WriteLine("I am a person.");
}}
}}
class Trainer : Personclass Trainer : Person
{{
public override void PrintName()public override void PrintName()
{{
Console.WriteLine("I am a trainer.");Console.WriteLine("I am a trainer.");
}}
}}
class Student : Personclass Student : Person
{{
public override void PrintName()public override void PrintName()
{{
Console.WriteLine("I am a student.");Console.WriteLine("I am a student.");
}}
}}
87. PolymorphismPolymorphism –– Example (2)Example (2)
static void Main()static void Main()
{{
Person[] persons =Person[] persons =
{{
new Person(),new Person(),
new Trainer(),new Trainer(),
new Student()new Student()
};};
foreach (Person p in persons)foreach (Person p in persons)
{{
Console.WriteLine(p);Console.WriteLine(p);
}}
// I am a person.// I am a person.
// I am a trainer.// I am a trainer.
// I am a student.// I am a student.
}}