SlideShare uma empresa Scribd logo
1 de 89
Object-Oriented
Programming with C#
Classes, Constructors, Properties, Events, Static
Members, Interfaces, Inheritance, Polymorphism
Svetlin Nakov
Telerik Corporation
www.telerik.com
Table of Contents
1. Defining Classes
2. Access Modifiers
3. Constructors
4. Fields, Constants and Properties
5. Static Members
6. Structures
7. Delegates and Events
8. Interfaces
9. Inheritance
10. Polymorphism
2
OOP and .NET
 In .NET Framework the object-oriented approach
has roots at the deepest architectural level
 All .NET applications are object-oriented
 All .NET languages are object-oriented
 The class concept from OOP has two realizations:
 Classes and structures
 There is no multiple inheritance in .NET
 Still classes can implement several interfaces at the
same time
3
Defining Classes
Classes in OOP
 Classes model real-world objects and define
 Attributes (state, properties, fields)
 Behavior (methods, operations)
 Classes describe structure of objects
 Objects describe particular instance of a class
 Properties hold information about the
modeled object relevant to the problem
 Operations implement object behavior
5
Classes in C#
 Classes in C# could have following members:
 Fields, constants, methods, properties,
indexers, events, operators, constructors,
destructors
 Inner types (inner classes, structures,
interfaces, delegates, ...)
 Members can have access modifiers (scope)
 public, private, protected, internal
 Members can be
 static (common) or specific for a given object
6
Simple Class Definition
public class Cat : Animal
{
private string name;
private string owner;
public Cat(string name, string owner)
{
this.name = name;
this.owner = owner;
}
public string Name
{
get { return name; }
set { name = value; }
}
Fields
Constructor
Property
Begin of class definition
Inherited (base) class
7
Simple Class Definition (2)
public string Owner
{
get { return owner;}
set { owner = value; }
}
public void SayMiau()
{
Console.WriteLine("Miauuuuuuu!");
}
}
Method
End of class
definition
8
Classes andTheir Members
 Classes have members
 Fields, constants, methods, properties,
indexers, events, operators, constructors,
destructors
 Inner types (inner classes, structures,
interfaces, delegates, ...)
 Members have modifiers (scope)
 public, private, protected, internal
 Members can be
 static (common) or for a given type
9
Class Definition and Members
 Class definition consists of:
 Class declaration
 Inherited class or implemented interfaces
 Fields (static or not)
 Constructors (static or not)
 Properties (static or not)
 Methods (static or not)
 Events, inner types, etc.
10
Access Modifiers
Public, Private, Protected, Internal
Access Modifiers
 Class members can have access modifiers
 Used to restrict the classes able to access them
 Supports the OOP principle "encapsulation"
 Class members can be:
 public – accessible from any class
 protected – accessible from the class itself and
all its descendent classes
 private – accessible from the class itself only
 internal – accessible from the current
assembly (used by default)
12
Defining Classes
Example
Task: Define Class Dog
 Our task is to define a simple class that
represents information about a dog
 The dog should have name and breed
 If there is no name or breed assigned
to the dog, it should be named "Balkan"
and its breed should be "Street excellent"
 It should be able to view and change the name
and the breed of the dog
 The dog should be able to bark
14
Defining Class Dog – Example
public class Dog
{
private string name;
private string breed;
public Dog()
{
this.name = "Balkan";
this.breed = "Street excellent";
}
public Dog(string name, string breed)
{
this.name = name;
this.breed = breed;
}
// (example continues)
15
Defining Class Dog – Example (2)
public string Name
{
get { return name; }
set { name = value; }
}
public string Breed
{
get { return breed; }
set { breed = value; }
}
public void SayBau()
{
Console.WriteLine("{0} said: Bauuuuuu!", name);
}
}
16
Using Classes and Objects
Using Classes
 How to use classes?
 Create a new instance
 Access the properties of the class
 Invoke methods
 Handle events
 How to define classes?
 Create new class and define its members
 Create new class using some other as base class
18
How to Use Classes (Non-Static)?
1. Create an instance
 Initialize fields
2. Manipulate instance
 Read / change properties
 Invoke methods
 Handle events
3. Release occupied resources
 Done automatically in most cases
19
Task: Dog Meeting
 Our task is as follows:
 Create 3 dogs
 First should be named “Sharo”, second – “Rex”
and the last – left without name
 Add all dogs in an array
 Iterate through the array elements and ask
each dog to bark
 Note:
 Use the Dog class from the previous example!
20
Dog Meeting – Example
static void Main()
{
Console.WriteLine("Enter first dog's name: ");
dogName = Console.ReadLine();
Console.WriteLine("Enter first dog's breed: ");
dogBreed = Console.ReadLine();
// Using the Dog constructor to set name and breed
Dog firstDog = new Dog(dogName, dogBreed);
Dog secondDog = new Dog();
Console.WriteLine("Enter second dog's name: ");
dogName = Console.ReadLine();
Console.WriteLine("Enter second dog's breed: ");
dogBreed = Console.ReadLine();
// Using properties to set name and breed
secondDog.Name = dogName;
secondDog.Breed = dogBreed;
}
21
Constructors
Defining and Using Class Constructors
What is Constructor?
 Constructors are special methods
 Invoked when creating a new instance of an
object
 Used to initialize the fields of the instance
 Constructors has the same name as the class
 Have no return type
 Can have parameters
 Can be private, protected, internal,
public
23
Defining Constructors
public class Point
{
private int xCoord;
private int yCoord;
// Simple default constructor
public Point()
{
xCoord = 0;
yCoord = 0;
}
// More code ...
}
 Class Point with parameterless constructor:
24
Defining Constructors (2)
public class Person
{
private string name;
private int age;
// Default constructor
public Person()
{
name = null;
age = 0;
}
// Constructor with parameters
public Person(string name, int age)
{
this.name = name;
this.age = age;
}
// More code comes here …
}
As rule constructors
should initialize all
own class fields.
25
Constructors and Initialization
 Pay attention when using inline initialization!
public class ClockAlarm
{
private int hours = 9; // Inline initialization
private int minutes = 0; // Inline initialization
// Default constructor
public ClockAlarm()
{ }
// Constructor with parameters
public ClockAlarm(int hours, int minutes)
{
this.hours = hours; // Invoked after the inline
this.minutes = minutes; // initialization!
}
// More code comes here …
}
26
Chaining Constructors Calls
 Reusing the constructors
public class Point
{
private int xCoord;
private int yCoord;
public Point() : this(0,0) // Reuse the constructor
{
}
public Point(int xCoord, int yCoord)
{
this.xCoord = xCoord;
this.yCoord = yCoord;
}
// More code comes here …
}
27
Fields, Constants
and Properties
Fields
 Fields contain data for the class instance
 Can be arbitrary type
 Have given scope
 Can be declared with a specific value
class Student
{
private string firstName;
private string lastName;
private int course = 1;
private string speciality;
protected Course[] coursesTaken;
private string remarks = "(no remarks)";
}
29
Constants
 Constant fields are defined like fields, but:
 Defined with const
 Must be initialized at their definition
 Their value can not be changed at runtime
public class MathConstants
{
public const string PI_SYMBOL = "π";
public const double PI = 3.1415926535897932385;
public const double E = 2.7182818284590452354;
public const double LN10 = 2.30258509299405;
public const double LN2 = 0.693147180559945;
}
30
Read-Only Fields
 Initialized at the definition or in the constructor
 Can not be modified further
 Defined with the keyword readonly
 Represent runtime constants
public class ReadOnlyExample
{
private readonly int size;
public ReadOnlyExample(int aSize)
{
size = aSize; // can not be further modified!
}
}
31
The Role of Properties
 Expose object's data to the outside world
 Control how the data is manipulated
 Properties can be:
 Read-only
 Write-only
 Read and write
 Give good level of abstraction
 Make writing code easier
32
Defining Properties in C#
 Properties should have:
 Access modifier (public, protected, etc.)
 Return type
 Unique name
 Get and / or Set part
 Can contain code processing data in specific
way, e.g. validation logic
33
Defining Properties – Example
public class Point
{
private int xCoord;
private int yCoord;
public int XCoord
{
get { return xCoord; }
set { xCoord = value; }
}
public int YCoord
{
get { return yCoord; }
set { yCoord = value; }
}
// More code ...
}
34
Dynamic Properties
 Properties are not obligatory bound to a class
field – can be calculated dynamically:
public class Rectangle
{
private float width;
private float height;
// More code ...
public float Area
{
get
{
return width * height;
}
}
}
35
Automatic Properties
 Properties could be defined without an
underlying field behind them
 It is automatically created by the C# compiler
36
class UserProfile
{
public int UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
…
UserProfile profile = new UserProfile() {
FirstName = "Steve",
LastName = "Balmer",
UserId = 91112
};
Static Members
Static vs. Instance Members
Static Members
 Static members are associated with a type
rather than with an instance
 Defined with the modifier static
 Static can be used for
 Fields
 Properties
 Methods
 Events
 Constructors
38
Static vs. Non-Static
 Static:
 Associated with a type, not with an instance
 Non-Static:
 The opposite, associated with an instance
 Static:
 Initialized just before the type is used for the
first time
 Non-Static:
 Initialized when the constructor is called
39
Static Members – Example
public class SqrtPrecalculated
{
public const int MAX_VALUE = 10000;
// Static field
private static int[] sqrtValues;
// Static constructor
private static SqrtPrecalculated()
{
sqrtValues = new int[MAX_VALUE + 1];
for (int i = 0; i < sqrtValues.Length; i++)
{
sqrtValues[i] = (int)Math.Sqrt(i);
}
}
// (example continues)
40
Static Members – Example (2)
// Static method
public static int GetSqrt(int value)
{
return sqrtValues[value];
}
// The Main() method is always static
static void Main()
{
Console.WriteLine(GetSqrt(254));
}
}
41
Structures
Structures
 Structures represent a combination of fields
with data
 Look like the classes, but are value types
 Their content is stored in the stack
 Transmitted by value
 Destroyed when go out of scope
 However classes are reference type and are
placed in the dynamic memory (heap)
 Their creation and destruction is slower
43
Structures – Example
struct Point
{
public int X, Y { get; set; }
}
struct Color
{
public byte RedValue { get; set; }
public byte GreenValue { get; set; }
public byte BlueValue { get; set; }
}
struct Square
{
public Point Location { get; set; }
public int Size { get; set; }
public Color BorderColor { get; set; }
public Color SurfaceColor { get; set; }
}
44
When to Use Structures?
 Use structures
 To make your type behave as a primitive type
 If you create many instances and after that you
free them – e.g. in a cycle
 Do not use structures
 When you often transmit your instances as
method parameters
 If you use collections without generics (too
much boxing / unboxing!)
45
Delegates and Events
What are Delegates?
 Delegates are reference types
 Describe the signature of a given method
 Number and types of the parameters
 The return type
 Their "values" are methods
 These methods correspond to the signature of
the delegate
47
What are Delegates? (2)
 Delegates are roughly similar to function
pointers in C and C++
 Contain a strongly-typed pointer (reference) to
a method
 They can point to both static or instance
methods
 Used to perform callbacks
48
Delegates – Example
// Declaration of a delegate
public delegate void SimpleDelegate(string param);
public class TestDelegate
{
public static void TestFunction(string param)
{
Console.WriteLine("I was called by a delegate.");
Console.WriteLine("I got parameter {0}.", param);
}
public static void Main()
{
// Instantiation of а delegate
SimpleDelegate simpleDelegate =
new SimpleDelegate(TestFunction);
// Invocation of the method, pointed by a delegate
simpleDelegate("test");
}
}
49
Anonymous Methods
 We are sometimes forced to create a class or a
method just for the sake of using a delegate
 The code involved is often relatively
short and simple
 Anonymous methods let you define an
nameless method called by a delegate
 Less coding
 Improved code readability
50
Using Delegates: StandardWay
class SomeClass
{
delegate void SomeDelegate(string str);
public void InvokeMethod()
{
SomeDelegate dlg = new SomeDelegate(SomeMethod);
dlg("Hello");
}
void SomeMethod(string str)
{
Console.WriteLine(str);
}
}
51
Using Anonymous Methods
 The same thing can be accomplished by using
an anonymous method:
class SomeClass
{
delegate void SomeDelegate(string str);
public void InvokeMethod()
{
SomeDelegate dlg = delegate(string str)
{
Console.WriteLine(str);
};
dlg("Hello");
}
}
52
Events
 In component-oriented programming the
components send events to their owner to notify
them when something happens
 E.g. when a button is pressed an event is raised
 The object which causes an event is called event
sender
 The object which receives an event is called
event receiver
 In order to be able to receive an event the event
receivers must first "subscribe for the event"
53
Events in .NET
 In the component model of .NET Framework
delegates and events provide mechanism for:
 Subscription to an event
 Sending an event
 Receiving an event
 Events in C# are special instances of delegates
declared by the C# keyword event
 Example (Button.Click):
public event EventHandler Click;
54
Events in .NET (2)
 The C# compiler automatically defines the +=
and -= operators for events
 += subscribe for an event
 -= unsubscribe for an event
 There are no other allowed operations
 Example:
Button button = new Button("OK");
button.Click += delegate
{
Console.WriteLine("Button clicked.");
};
55
Events vs. Delegates
 Events are not the same as member fields of
type delegate
 The event is processed by a delegate
 Events can be members of an interface unlike
delegates
 Calling of an event can only be done in the
class it is defined in
 By default the access to the events is
synchronized (thread-safe)
public MyDelegate m; public event MyDelegate m;≠
56
System.EventHandler Delegate
 Defines a reference to a callback method,
which handles events
 No additional information is sent
 Used in many occasions internally in .NET
 E.g. in ASP.NET and Windows Forms
 The EventArgs class is base class with no
information about the event
 Sometimes delegates derive from it
public delegate void EventHandler(
object sender, EventArgs e);
57
EventHandler – Example
public class Button
{
public event EventHandler Click;
public event EventHandler GotFocus;
public event EventHandler TextChanged;
…
}
public class ButtonTest
{
private static void Button_Click(object sender,
EventArgs eventArgs)
{
Console.WriteLine("Call Button_Click() event");
}
public static void Main()
{
Button button = new Button();
button.Click += Button_Click;
}
}
58
Interfaces and
Abstract Classes
Interfaces
 Describe a group of methods (operations),
properties and events
 Can be implemented by given class or
structure
 Define only the methods’ prototypes
 No concrete implementation
 Can be used to define abstract data types
 Can not be instantiated
 Members do not have scope modifier
and by default the scope is public
60
Interfaces – Example
public interface IPerson
{
string Name // property Name
{
get;
set;
}
DateTime DateOfBirth // property DateOfBirth
{
get;
set;
}
int Age // property Age (read-only)
{
get;
set;
}
}
61
Interfaces – Example (2)
interface IShape
{
void SetPosition(int x, int y);
int CalculateSurface();
}
interface IMovable
{
void Move(int deltaX, int deltaY);
}
interface IResizable
{
void Resize(int weight);
void Resize(int weightX, int weightY);
void ResizeByX(int weightX);
void ResizeByY(int weightY);
}
62
Interface Implementation
 Classes and structures can implement
(support) one or many interfaces
 Interface realization must implement all its
methods
 If some methods do not have implementation
the class or structure have to be declared
as an abstract
63
Interface Implementation –
Example
class Rectangle : IShape, IMovable
{
private int x, y, width, height;
public void SetPosition(int x, int y) // IShape
{
this.x = x;
this.y = y;
}
public int CalculateSurface() // IShape
{
return this.width * this.height;
}
public void Move(int deltaX, int deltaY) // IMovable
{
this.x += deltaX;
this.y += deltaY;
}
}
64
Abstract Classes
 Abstract method is a method without
implementation
 Left empty to be implemented by some
descendant class
 When a class contains at least one abstract
method, it is called abstract class
 Mix between class and interface
 Inheritors are obligated to
implement their abstract methods
 Can not be directly instantiated
65
Abstract Class – Example
abstract class MovableShape : IShape, IMovable
{
private int x, y;
public void Move(int deltaX, int deltaY)
{
this.x += deltaX;
this.y += deltaY;
}
public void SetPosition(int x, int y)
{
this.x = x;
this.y = y;
}
public abstract int CalculateSurface();
}
66
Cohesion and Coupling
Cohesion
 Cohesion describes how closely all the routines
in a class or all the code in a routine support a
central purpose
 Cohesion must be strong
 Classes must contain strongly related
functionality and aim for single purpose
 Cohesion is a useful tool for managing
complexity
 Well-defined abstractions keep cohesion strong
68
Good and Bad Cohesion
 Good cohesion: hard disk, CD-ROM, floppy
 Bad cohesion: spaghetti code
69
Strong Cohesion
 Strong cohesion example
 Class Math that has methods and constants:
 Sin(), Cos(), Asin(), Sqrt(), Pow(), Exp()
 Math.PI, Math.E
double sideA = 40, sideB = 69;
double angleAB = Math.PI / 3;
double sideC =
Math.Pow(sideA, 2) + Math.Pow(sideB, 2) -
2 * sideA * sideB * Math.Cos(angleAB);
double sidesSqrtSum = Math.Sqrt(sideA) +
Math.Sqrt(sideB) + Math.Sqrt(sideC);
70
Bad Cohesion
 Example of bad cohesion
 Class Magic that has all these methods:
 Another example:
MagicClass.MakePizza("Fat Pepperoni");
MagicClass.WithdrawMoney("999e6");
MagicClass.OpenDBConnection();
public void PrintDocument(Document d);
public void SendEmail(string recipient, string
subject, string text);
public void CalculateDistanceBetweenPoints(int x1,
int y1, int x2, int y2)
71
Coupling
 Coupling describes how tightly a class or
routine is related to other classes or routines
 Coupling must be kept loose
 Modules must depend little on each other
 All classes and routines must have small, direct,
visible, and flexible relations to other classes
and routines
 One module must be easily used by other
modules
72
Loose andTight Coupling
 Loose Coupling:
 Easily replace old HDD
 Easily place this HDD to
another motherboard
 Tight Coupling:
 Where is the video card?
 Can you change the
video card?
73
Loose Coupling – Example
class Report
{
public bool LoadFromFile(string fileName) {…}
public bool SaveToFile(string fileName) {…}
}
class Printer
{
public static int Print(Report report) {…}
}
class LooseCouplingExample
{
static void Main()
{
Report myReport = new Report();
myReport.LoadFromFile("C:DailyReport.rep");
Printer.Print(myReport);
}
}
74
Tight Coupling – Example
class MathParams
{
public static double operand;
public static double result;
}
class MathUtil
{
public static void Sqrt()
{
MathParams.result = CalcSqrt(MathParams.operand);
}
}
class Example
{
static void Main()
{
MathParams.operand = 64;
MathUtil.Sqrt();
Console.WriteLine(MathParams.result);
}
}
75
Spaghetti Code
 Combination of bad cohesion and tight coupling
(spaghetti code):
class Report
{
public void Print() {…}
public void InitPrinter() {…}
public void LoadPrinterDriver(string fileName) {…}
public bool SaveReport(string fileName) {…}
public void SetPrinter(string printer) {…}
}
class Printer
{
public void SetFileName() {…}
public static bool LoadReport() {…}
public static bool CheckReport() {…}
}
76
Inheritance
Inheritance
 Inheritance is the ability of a class to implicitly
gain all members from another class
 Inheritance is fundamental concept in OOP
 The class whose methods are inherited is
called base (parent) class
 The class that gains new functionality is called
derived (child) class
 Inheritance establishes an is-a relationship
between classes: A is B
78
Inheritance (2)
 All class members are inherited
 Fields, methods, properties, …
 In C# classes could be inherited
 The structures in C# could not be inherited
 Inheritance allows creating deep inheritance
hierarchies
 In .NET there is no multiple inheritance,
except when implementing interfaces
79
How to Define Inheritance?
 We must specify the name of the base class
after the name of the derived
 In the constructor of the derived class we use
the keyword base to invoke the constructor of
the base class
public class Shape
{...}
public class Circle : Shape
{...}
public Circle (int x, int y) : base(x)
{...}
80
Inheritance – Example
public class Mammal
{
private int age;
public Mammal(int age)
{
this.age = age;
}
public int Age
{
get { return age; }
set { age = value; }
}
public void Sleep()
{
Console.WriteLine("Shhh! I'm sleeping!");
}
}
81
Inheritance – Example (2)
public class Dog : Mammal
{
private string breed;
public Dog(int age, string breed): base(age)
{
this.breed = breed;
}
public string Breed
{
get { return breed; }
set { breed = value; }
}
public void WagTail()
{
Console.WriteLine("Tail wagging...");
}
}
82
Inheritance – Example (3)
static void Main()
{
// Create 5 years old mammal
Mamal mamal = new Mamal(5);
Console.WriteLine(mamal.Age);
mamal.Sleep();
// Create a bulldog, 3 years old
Dog dog = new Dog("Bulldog", 3);
dog.Sleep();
dog.Age = 4;
Console.WriteLine("Age: {0}", dog.Age);
Console.WriteLine("Breed: {0}", dog.Breed);
dog.WagTail();
}
83
Polymorphism
Polymorphism
 Polymorphism is fundamental concept in
OOP
 The ability to handle the objects of a specific
class as instances of its parent class and to call
abstract functionality
 Polymorphism allows creating hierarchies with
more valuable logical structure
 Allows invoking abstract functionality without
caring how and where it is implemented
85
Polymorphism (2)
 Polymorphism is usually implemented
through:
 Virtual methods (virtual)
 Abstract methods (abstract)
 Methods from an interface (interface)
 In C# to override virtual method the keyword
override is used
 C# allows hiding virtual methods in derived
classes by the keyword new
86
Polymorphism – Example
class Person
{
public virtual void PrintName()
{
Console.WriteLine("I am a person.");
}
}
class Trainer : Person
{
public override void PrintName()
{
Console.WriteLine("I am a trainer.");
}
}
class Student : Person
{
public override void PrintName()
{
Console.WriteLine("I am a student.");
}
}
87
Polymorphism – Example (2)
static void Main()
{
Person[] persons =
{
new Person(),
new Trainer(),
new Student()
};
foreach (Person p in persons)
{
Console.WriteLine(p);
}
// I am a person.
// I am a trainer.
// I am a student.
}
88
Questions?
Object-Oriented
Programming with C#
http://schoolacademy.telerik.com

Mais conteúdo relacionado

Mais procurados (20)

Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in java
 
operator overloading
operator overloadingoperator overloading
operator overloading
 
Friend function in c++
Friend function in c++ Friend function in c++
Friend function in c++
 
Scope rules : local and global variables
Scope rules : local and global variablesScope rules : local and global variables
Scope rules : local and global variables
 
Constructors and Destructor in C++
Constructors and Destructor in C++Constructors and Destructor in C++
Constructors and Destructor in C++
 
OOPS Basics With Example
OOPS Basics With ExampleOOPS Basics With Example
OOPS Basics With Example
 
C++ presentation
C++ presentationC++ presentation
C++ presentation
 
class and objects
class and objectsclass and objects
class and objects
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Abstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core JavaAbstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core Java
 
Access specifier
Access specifierAccess specifier
Access specifier
 
Introduction to web programming with JavaScript
Introduction to web programming with JavaScriptIntroduction to web programming with JavaScript
Introduction to web programming with JavaScript
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 
Java class,object,method introduction
Java class,object,method introductionJava class,object,method introduction
Java class,object,method introduction
 
Structure in C language
Structure in C languageStructure in C language
Structure in C language
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and Destructor
 
Friend function
Friend functionFriend function
Friend function
 
Arrays
ArraysArrays
Arrays
 
Templates in c++
Templates in c++Templates in c++
Templates in c++
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 

Semelhante a Object-Oriented Programming with C#

14. Defining Classes
14. Defining Classes14. Defining Classes
14. Defining ClassesIntro C# Book
 
Defining classes-part-i-constructors-properties
Defining classes-part-i-constructors-propertiesDefining classes-part-i-constructors-properties
Defining classes-part-i-constructors-propertiesCtOlaf
 
03 classes interfaces_principlesofoop
03 classes interfaces_principlesofoop03 classes interfaces_principlesofoop
03 classes interfaces_principlesofoopVladislav Hadzhiyski
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0BG Java EE Course
 
20 Object-oriented programming principles
20 Object-oriented programming principles20 Object-oriented programming principles
20 Object-oriented programming principlesmaznabili
 
Object oriented programming Fundamental Concepts
Object oriented programming Fundamental ConceptsObject oriented programming Fundamental Concepts
Object oriented programming Fundamental ConceptsBharat Kalia
 
02-OOP with Java.ppt
02-OOP with Java.ppt02-OOP with Java.ppt
02-OOP with Java.pptEmanAsem4
 
Object-oriented Programming-with C#
Object-oriented Programming-with C#Object-oriented Programming-with C#
Object-oriented Programming-with C#Doncho Minkov
 
C# (This keyword, Properties, Inheritance, Base Keyword)
C# (This keyword, Properties, Inheritance, Base Keyword)C# (This keyword, Properties, Inheritance, Base Keyword)
C# (This keyword, Properties, Inheritance, Base Keyword)Umar Farooq
 
14 Defining classes
14 Defining classes14 Defining classes
14 Defining classesmaznabili
 
Java oops PPT
Java oops PPTJava oops PPT
Java oops PPTkishu0005
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slotsmha4
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slotsmha4
 
20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental Principles20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental PrinciplesIntro C# Book
 
Ccourse 140618093931-phpapp02
Ccourse 140618093931-phpapp02Ccourse 140618093931-phpapp02
Ccourse 140618093931-phpapp02Getachew Ganfur
 
C++ Programming Course
C++ Programming CourseC++ Programming Course
C++ Programming CourseDennis Chang
 
Is2215 lecture2 student(2)
Is2215 lecture2 student(2)Is2215 lecture2 student(2)
Is2215 lecture2 student(2)dannygriff1
 

Semelhante a Object-Oriented Programming with C# (20)

14. Defining Classes
14. Defining Classes14. Defining Classes
14. Defining Classes
 
Defining classes-part-i-constructors-properties
Defining classes-part-i-constructors-propertiesDefining classes-part-i-constructors-properties
Defining classes-part-i-constructors-properties
 
03 classes interfaces_principlesofoop
03 classes interfaces_principlesofoop03 classes interfaces_principlesofoop
03 classes interfaces_principlesofoop
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0
 
20 Object-oriented programming principles
20 Object-oriented programming principles20 Object-oriented programming principles
20 Object-oriented programming principles
 
Object oriented programming Fundamental Concepts
Object oriented programming Fundamental ConceptsObject oriented programming Fundamental Concepts
Object oriented programming Fundamental Concepts
 
02-OOP with Java.ppt
02-OOP with Java.ppt02-OOP with Java.ppt
02-OOP with Java.ppt
 
Object-oriented Programming-with C#
Object-oriented Programming-with C#Object-oriented Programming-with C#
Object-oriented Programming-with C#
 
C# (This keyword, Properties, Inheritance, Base Keyword)
C# (This keyword, Properties, Inheritance, Base Keyword)C# (This keyword, Properties, Inheritance, Base Keyword)
C# (This keyword, Properties, Inheritance, Base Keyword)
 
14 Defining classes
14 Defining classes14 Defining classes
14 Defining classes
 
Java oops PPT
Java oops PPTJava oops PPT
Java oops PPT
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 
20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental Principles20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental Principles
 
Ccourse 140618093931-phpapp02
Ccourse 140618093931-phpapp02Ccourse 140618093931-phpapp02
Ccourse 140618093931-phpapp02
 
C++ Programming Course
C++ Programming CourseC++ Programming Course
C++ Programming Course
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
 
Python_Unit_2 OOPS.pptx
Python_Unit_2  OOPS.pptxPython_Unit_2  OOPS.pptx
Python_Unit_2 OOPS.pptx
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
 
Is2215 lecture2 student(2)
Is2215 lecture2 student(2)Is2215 lecture2 student(2)
Is2215 lecture2 student(2)
 

Mais de Svetlin Nakov

BG-IT-Edu: отворено учебно съдържание за ИТ учители
BG-IT-Edu: отворено учебно съдържание за ИТ учителиBG-IT-Edu: отворено учебно съдържание за ИТ учители
BG-IT-Edu: отворено учебно съдържание за ИТ учителиSvetlin Nakov
 
Programming World in 2024
Programming World in 2024Programming World in 2024
Programming World in 2024Svetlin Nakov
 
AI Tools for Business and Startups
AI Tools for Business and StartupsAI Tools for Business and Startups
AI Tools for Business and StartupsSvetlin Nakov
 
AI Tools for Scientists - Nakov (Oct 2023)
AI Tools for Scientists - Nakov (Oct 2023)AI Tools for Scientists - Nakov (Oct 2023)
AI Tools for Scientists - Nakov (Oct 2023)Svetlin Nakov
 
AI Tools for Entrepreneurs
AI Tools for EntrepreneursAI Tools for Entrepreneurs
AI Tools for EntrepreneursSvetlin Nakov
 
Bulgarian Tech Industry - Nakov at Dev.BG All in One Conference 2023
Bulgarian Tech Industry - Nakov at Dev.BG All in One Conference 2023Bulgarian Tech Industry - Nakov at Dev.BG All in One Conference 2023
Bulgarian Tech Industry - Nakov at Dev.BG All in One Conference 2023Svetlin Nakov
 
AI Tools for Business and Personal Life
AI Tools for Business and Personal LifeAI Tools for Business and Personal Life
AI Tools for Business and Personal LifeSvetlin Nakov
 
Дипломна работа: учебно съдържание по ООП - Светлин Наков
Дипломна работа: учебно съдържание по ООП - Светлин НаковДипломна работа: учебно съдържание по ООП - Светлин Наков
Дипломна работа: учебно съдържание по ООП - Светлин НаковSvetlin Nakov
 
Дипломна работа: учебно съдържание по ООП
Дипломна работа: учебно съдържание по ООПДипломна работа: учебно съдържание по ООП
Дипломна работа: учебно съдържание по ООПSvetlin Nakov
 
Свободно ИТ учебно съдържание за учители по програмиране и ИТ
Свободно ИТ учебно съдържание за учители по програмиране и ИТСвободно ИТ учебно съдържание за учители по програмиране и ИТ
Свободно ИТ учебно съдържание за учители по програмиране и ИТSvetlin Nakov
 
AI and the Professions of the Future
AI and the Professions of the FutureAI and the Professions of the Future
AI and the Professions of the FutureSvetlin Nakov
 
Programming Languages Trends for 2023
Programming Languages Trends for 2023Programming Languages Trends for 2023
Programming Languages Trends for 2023Svetlin Nakov
 
IT Professions and How to Become a Developer
IT Professions and How to Become a DeveloperIT Professions and How to Become a Developer
IT Professions and How to Become a DeveloperSvetlin Nakov
 
GitHub Actions (Nakov at RuseConf, Sept 2022)
GitHub Actions (Nakov at RuseConf, Sept 2022)GitHub Actions (Nakov at RuseConf, Sept 2022)
GitHub Actions (Nakov at RuseConf, Sept 2022)Svetlin Nakov
 
IT Professions and Their Future
IT Professions and Their FutureIT Professions and Their Future
IT Professions and Their FutureSvetlin Nakov
 
How to Become a QA Engineer and Start a Job
How to Become a QA Engineer and Start a JobHow to Become a QA Engineer and Start a Job
How to Become a QA Engineer and Start a JobSvetlin Nakov
 
Призвание и цели: моята рецепта
Призвание и цели: моята рецептаПризвание и цели: моята рецепта
Призвание и цели: моята рецептаSvetlin Nakov
 
What Mongolian IT Industry Can Learn from Bulgaria?
What Mongolian IT Industry Can Learn from Bulgaria?What Mongolian IT Industry Can Learn from Bulgaria?
What Mongolian IT Industry Can Learn from Bulgaria?Svetlin Nakov
 
How to Become a Software Developer - Nakov in Mongolia (Oct 2022)
How to Become a Software Developer - Nakov in Mongolia (Oct 2022)How to Become a Software Developer - Nakov in Mongolia (Oct 2022)
How to Become a Software Developer - Nakov in Mongolia (Oct 2022)Svetlin Nakov
 
Blockchain and DeFi Overview (Nakov, Sept 2021)
Blockchain and DeFi Overview (Nakov, Sept 2021)Blockchain and DeFi Overview (Nakov, Sept 2021)
Blockchain and DeFi Overview (Nakov, Sept 2021)Svetlin Nakov
 

Mais de Svetlin Nakov (20)

BG-IT-Edu: отворено учебно съдържание за ИТ учители
BG-IT-Edu: отворено учебно съдържание за ИТ учителиBG-IT-Edu: отворено учебно съдържание за ИТ учители
BG-IT-Edu: отворено учебно съдържание за ИТ учители
 
Programming World in 2024
Programming World in 2024Programming World in 2024
Programming World in 2024
 
AI Tools for Business and Startups
AI Tools for Business and StartupsAI Tools for Business and Startups
AI Tools for Business and Startups
 
AI Tools for Scientists - Nakov (Oct 2023)
AI Tools for Scientists - Nakov (Oct 2023)AI Tools for Scientists - Nakov (Oct 2023)
AI Tools for Scientists - Nakov (Oct 2023)
 
AI Tools for Entrepreneurs
AI Tools for EntrepreneursAI Tools for Entrepreneurs
AI Tools for Entrepreneurs
 
Bulgarian Tech Industry - Nakov at Dev.BG All in One Conference 2023
Bulgarian Tech Industry - Nakov at Dev.BG All in One Conference 2023Bulgarian Tech Industry - Nakov at Dev.BG All in One Conference 2023
Bulgarian Tech Industry - Nakov at Dev.BG All in One Conference 2023
 
AI Tools for Business and Personal Life
AI Tools for Business and Personal LifeAI Tools for Business and Personal Life
AI Tools for Business and Personal Life
 
Дипломна работа: учебно съдържание по ООП - Светлин Наков
Дипломна работа: учебно съдържание по ООП - Светлин НаковДипломна работа: учебно съдържание по ООП - Светлин Наков
Дипломна работа: учебно съдържание по ООП - Светлин Наков
 
Дипломна работа: учебно съдържание по ООП
Дипломна работа: учебно съдържание по ООПДипломна работа: учебно съдържание по ООП
Дипломна работа: учебно съдържание по ООП
 
Свободно ИТ учебно съдържание за учители по програмиране и ИТ
Свободно ИТ учебно съдържание за учители по програмиране и ИТСвободно ИТ учебно съдържание за учители по програмиране и ИТ
Свободно ИТ учебно съдържание за учители по програмиране и ИТ
 
AI and the Professions of the Future
AI and the Professions of the FutureAI and the Professions of the Future
AI and the Professions of the Future
 
Programming Languages Trends for 2023
Programming Languages Trends for 2023Programming Languages Trends for 2023
Programming Languages Trends for 2023
 
IT Professions and How to Become a Developer
IT Professions and How to Become a DeveloperIT Professions and How to Become a Developer
IT Professions and How to Become a Developer
 
GitHub Actions (Nakov at RuseConf, Sept 2022)
GitHub Actions (Nakov at RuseConf, Sept 2022)GitHub Actions (Nakov at RuseConf, Sept 2022)
GitHub Actions (Nakov at RuseConf, Sept 2022)
 
IT Professions and Their Future
IT Professions and Their FutureIT Professions and Their Future
IT Professions and Their Future
 
How to Become a QA Engineer and Start a Job
How to Become a QA Engineer and Start a JobHow to Become a QA Engineer and Start a Job
How to Become a QA Engineer and Start a Job
 
Призвание и цели: моята рецепта
Призвание и цели: моята рецептаПризвание и цели: моята рецепта
Призвание и цели: моята рецепта
 
What Mongolian IT Industry Can Learn from Bulgaria?
What Mongolian IT Industry Can Learn from Bulgaria?What Mongolian IT Industry Can Learn from Bulgaria?
What Mongolian IT Industry Can Learn from Bulgaria?
 
How to Become a Software Developer - Nakov in Mongolia (Oct 2022)
How to Become a Software Developer - Nakov in Mongolia (Oct 2022)How to Become a Software Developer - Nakov in Mongolia (Oct 2022)
How to Become a Software Developer - Nakov in Mongolia (Oct 2022)
 
Blockchain and DeFi Overview (Nakov, Sept 2021)
Blockchain and DeFi Overview (Nakov, Sept 2021)Blockchain and DeFi Overview (Nakov, Sept 2021)
Blockchain and DeFi Overview (Nakov, Sept 2021)
 

Object-Oriented Programming with C#

  • 1. Object-Oriented Programming with C# Classes, Constructors, Properties, Events, Static Members, Interfaces, Inheritance, Polymorphism Svetlin Nakov Telerik Corporation www.telerik.com
  • 2. Table of Contents 1. Defining Classes 2. Access Modifiers 3. Constructors 4. Fields, Constants and Properties 5. Static Members 6. Structures 7. Delegates and Events 8. Interfaces 9. Inheritance 10. Polymorphism 2
  • 3. OOP and .NET  In .NET Framework the object-oriented approach has roots at the deepest architectural level  All .NET applications are object-oriented  All .NET languages are object-oriented  The class concept from OOP has two realizations:  Classes and structures  There is no multiple inheritance in .NET  Still classes can implement several interfaces at the same time 3
  • 5. Classes in OOP  Classes model real-world objects and define  Attributes (state, properties, fields)  Behavior (methods, operations)  Classes describe structure of objects  Objects describe particular instance of a class  Properties hold information about the modeled object relevant to the problem  Operations implement object behavior 5
  • 6. Classes in C#  Classes in C# could have following members:  Fields, constants, methods, properties, indexers, events, operators, constructors, destructors  Inner types (inner classes, structures, interfaces, delegates, ...)  Members can have access modifiers (scope)  public, private, protected, internal  Members can be  static (common) or specific for a given object 6
  • 7. Simple Class Definition public class Cat : Animal { private string name; private string owner; public Cat(string name, string owner) { this.name = name; this.owner = owner; } public string Name { get { return name; } set { name = value; } } Fields Constructor Property Begin of class definition Inherited (base) class 7
  • 8. Simple Class Definition (2) public string Owner { get { return owner;} set { owner = value; } } public void SayMiau() { Console.WriteLine("Miauuuuuuu!"); } } Method End of class definition 8
  • 9. Classes andTheir Members  Classes have members  Fields, constants, methods, properties, indexers, events, operators, constructors, destructors  Inner types (inner classes, structures, interfaces, delegates, ...)  Members have modifiers (scope)  public, private, protected, internal  Members can be  static (common) or for a given type 9
  • 10. Class Definition and Members  Class definition consists of:  Class declaration  Inherited class or implemented interfaces  Fields (static or not)  Constructors (static or not)  Properties (static or not)  Methods (static or not)  Events, inner types, etc. 10
  • 11. Access Modifiers Public, Private, Protected, Internal
  • 12. Access Modifiers  Class members can have access modifiers  Used to restrict the classes able to access them  Supports the OOP principle "encapsulation"  Class members can be:  public – accessible from any class  protected – accessible from the class itself and all its descendent classes  private – accessible from the class itself only  internal – accessible from the current assembly (used by default) 12
  • 14. Task: Define Class Dog  Our task is to define a simple class that represents information about a dog  The dog should have name and breed  If there is no name or breed assigned to the dog, it should be named "Balkan" and its breed should be "Street excellent"  It should be able to view and change the name and the breed of the dog  The dog should be able to bark 14
  • 15. Defining Class Dog – Example public class Dog { private string name; private string breed; public Dog() { this.name = "Balkan"; this.breed = "Street excellent"; } public Dog(string name, string breed) { this.name = name; this.breed = breed; } // (example continues) 15
  • 16. Defining Class Dog – Example (2) public string Name { get { return name; } set { name = value; } } public string Breed { get { return breed; } set { breed = value; } } public void SayBau() { Console.WriteLine("{0} said: Bauuuuuu!", name); } } 16
  • 17. Using Classes and Objects
  • 18. Using Classes  How to use classes?  Create a new instance  Access the properties of the class  Invoke methods  Handle events  How to define classes?  Create new class and define its members  Create new class using some other as base class 18
  • 19. How to Use Classes (Non-Static)? 1. Create an instance  Initialize fields 2. Manipulate instance  Read / change properties  Invoke methods  Handle events 3. Release occupied resources  Done automatically in most cases 19
  • 20. Task: Dog Meeting  Our task is as follows:  Create 3 dogs  First should be named “Sharo”, second – “Rex” and the last – left without name  Add all dogs in an array  Iterate through the array elements and ask each dog to bark  Note:  Use the Dog class from the previous example! 20
  • 21. Dog Meeting – Example static void Main() { Console.WriteLine("Enter first dog's name: "); dogName = Console.ReadLine(); Console.WriteLine("Enter first dog's breed: "); dogBreed = Console.ReadLine(); // Using the Dog constructor to set name and breed Dog firstDog = new Dog(dogName, dogBreed); Dog secondDog = new Dog(); Console.WriteLine("Enter second dog's name: "); dogName = Console.ReadLine(); Console.WriteLine("Enter second dog's breed: "); dogBreed = Console.ReadLine(); // Using properties to set name and breed secondDog.Name = dogName; secondDog.Breed = dogBreed; } 21
  • 22. Constructors Defining and Using Class Constructors
  • 23. What is Constructor?  Constructors are special methods  Invoked when creating a new instance of an object  Used to initialize the fields of the instance  Constructors has the same name as the class  Have no return type  Can have parameters  Can be private, protected, internal, public 23
  • 24. Defining Constructors public class Point { private int xCoord; private int yCoord; // Simple default constructor public Point() { xCoord = 0; yCoord = 0; } // More code ... }  Class Point with parameterless constructor: 24
  • 25. Defining Constructors (2) public class Person { private string name; private int age; // Default constructor public Person() { name = null; age = 0; } // Constructor with parameters public Person(string name, int age) { this.name = name; this.age = age; } // More code comes here … } As rule constructors should initialize all own class fields. 25
  • 26. Constructors and Initialization  Pay attention when using inline initialization! public class ClockAlarm { private int hours = 9; // Inline initialization private int minutes = 0; // Inline initialization // Default constructor public ClockAlarm() { } // Constructor with parameters public ClockAlarm(int hours, int minutes) { this.hours = hours; // Invoked after the inline this.minutes = minutes; // initialization! } // More code comes here … } 26
  • 27. Chaining Constructors Calls  Reusing the constructors public class Point { private int xCoord; private int yCoord; public Point() : this(0,0) // Reuse the constructor { } public Point(int xCoord, int yCoord) { this.xCoord = xCoord; this.yCoord = yCoord; } // More code comes here … } 27
  • 29. Fields  Fields contain data for the class instance  Can be arbitrary type  Have given scope  Can be declared with a specific value class Student { private string firstName; private string lastName; private int course = 1; private string speciality; protected Course[] coursesTaken; private string remarks = "(no remarks)"; } 29
  • 30. Constants  Constant fields are defined like fields, but:  Defined with const  Must be initialized at their definition  Their value can not be changed at runtime public class MathConstants { public const string PI_SYMBOL = "π"; public const double PI = 3.1415926535897932385; public const double E = 2.7182818284590452354; public const double LN10 = 2.30258509299405; public const double LN2 = 0.693147180559945; } 30
  • 31. Read-Only Fields  Initialized at the definition or in the constructor  Can not be modified further  Defined with the keyword readonly  Represent runtime constants public class ReadOnlyExample { private readonly int size; public ReadOnlyExample(int aSize) { size = aSize; // can not be further modified! } } 31
  • 32. The Role of Properties  Expose object's data to the outside world  Control how the data is manipulated  Properties can be:  Read-only  Write-only  Read and write  Give good level of abstraction  Make writing code easier 32
  • 33. Defining Properties in C#  Properties should have:  Access modifier (public, protected, etc.)  Return type  Unique name  Get and / or Set part  Can contain code processing data in specific way, e.g. validation logic 33
  • 34. Defining Properties – Example public class Point { private int xCoord; private int yCoord; public int XCoord { get { return xCoord; } set { xCoord = value; } } public int YCoord { get { return yCoord; } set { yCoord = value; } } // More code ... } 34
  • 35. Dynamic Properties  Properties are not obligatory bound to a class field – can be calculated dynamically: public class Rectangle { private float width; private float height; // More code ... public float Area { get { return width * height; } } } 35
  • 36. Automatic Properties  Properties could be defined without an underlying field behind them  It is automatically created by the C# compiler 36 class UserProfile { public int UserId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } … UserProfile profile = new UserProfile() { FirstName = "Steve", LastName = "Balmer", UserId = 91112 };
  • 37. Static Members Static vs. Instance Members
  • 38. Static Members  Static members are associated with a type rather than with an instance  Defined with the modifier static  Static can be used for  Fields  Properties  Methods  Events  Constructors 38
  • 39. Static vs. Non-Static  Static:  Associated with a type, not with an instance  Non-Static:  The opposite, associated with an instance  Static:  Initialized just before the type is used for the first time  Non-Static:  Initialized when the constructor is called 39
  • 40. Static Members – Example public class SqrtPrecalculated { public const int MAX_VALUE = 10000; // Static field private static int[] sqrtValues; // Static constructor private static SqrtPrecalculated() { sqrtValues = new int[MAX_VALUE + 1]; for (int i = 0; i < sqrtValues.Length; i++) { sqrtValues[i] = (int)Math.Sqrt(i); } } // (example continues) 40
  • 41. Static Members – Example (2) // Static method public static int GetSqrt(int value) { return sqrtValues[value]; } // The Main() method is always static static void Main() { Console.WriteLine(GetSqrt(254)); } } 41
  • 43. Structures  Structures represent a combination of fields with data  Look like the classes, but are value types  Their content is stored in the stack  Transmitted by value  Destroyed when go out of scope  However classes are reference type and are placed in the dynamic memory (heap)  Their creation and destruction is slower 43
  • 44. Structures – Example struct Point { public int X, Y { get; set; } } struct Color { public byte RedValue { get; set; } public byte GreenValue { get; set; } public byte BlueValue { get; set; } } struct Square { public Point Location { get; set; } public int Size { get; set; } public Color BorderColor { get; set; } public Color SurfaceColor { get; set; } } 44
  • 45. When to Use Structures?  Use structures  To make your type behave as a primitive type  If you create many instances and after that you free them – e.g. in a cycle  Do not use structures  When you often transmit your instances as method parameters  If you use collections without generics (too much boxing / unboxing!) 45
  • 47. What are Delegates?  Delegates are reference types  Describe the signature of a given method  Number and types of the parameters  The return type  Their "values" are methods  These methods correspond to the signature of the delegate 47
  • 48. What are Delegates? (2)  Delegates are roughly similar to function pointers in C and C++  Contain a strongly-typed pointer (reference) to a method  They can point to both static or instance methods  Used to perform callbacks 48
  • 49. Delegates – Example // Declaration of a delegate public delegate void SimpleDelegate(string param); public class TestDelegate { public static void TestFunction(string param) { Console.WriteLine("I was called by a delegate."); Console.WriteLine("I got parameter {0}.", param); } public static void Main() { // Instantiation of а delegate SimpleDelegate simpleDelegate = new SimpleDelegate(TestFunction); // Invocation of the method, pointed by a delegate simpleDelegate("test"); } } 49
  • 50. Anonymous Methods  We are sometimes forced to create a class or a method just for the sake of using a delegate  The code involved is often relatively short and simple  Anonymous methods let you define an nameless method called by a delegate  Less coding  Improved code readability 50
  • 51. Using Delegates: StandardWay class SomeClass { delegate void SomeDelegate(string str); public void InvokeMethod() { SomeDelegate dlg = new SomeDelegate(SomeMethod); dlg("Hello"); } void SomeMethod(string str) { Console.WriteLine(str); } } 51
  • 52. Using Anonymous Methods  The same thing can be accomplished by using an anonymous method: class SomeClass { delegate void SomeDelegate(string str); public void InvokeMethod() { SomeDelegate dlg = delegate(string str) { Console.WriteLine(str); }; dlg("Hello"); } } 52
  • 53. Events  In component-oriented programming the components send events to their owner to notify them when something happens  E.g. when a button is pressed an event is raised  The object which causes an event is called event sender  The object which receives an event is called event receiver  In order to be able to receive an event the event receivers must first "subscribe for the event" 53
  • 54. Events in .NET  In the component model of .NET Framework delegates and events provide mechanism for:  Subscription to an event  Sending an event  Receiving an event  Events in C# are special instances of delegates declared by the C# keyword event  Example (Button.Click): public event EventHandler Click; 54
  • 55. Events in .NET (2)  The C# compiler automatically defines the += and -= operators for events  += subscribe for an event  -= unsubscribe for an event  There are no other allowed operations  Example: Button button = new Button("OK"); button.Click += delegate { Console.WriteLine("Button clicked."); }; 55
  • 56. Events vs. Delegates  Events are not the same as member fields of type delegate  The event is processed by a delegate  Events can be members of an interface unlike delegates  Calling of an event can only be done in the class it is defined in  By default the access to the events is synchronized (thread-safe) public MyDelegate m; public event MyDelegate m;≠ 56
  • 57. System.EventHandler Delegate  Defines a reference to a callback method, which handles events  No additional information is sent  Used in many occasions internally in .NET  E.g. in ASP.NET and Windows Forms  The EventArgs class is base class with no information about the event  Sometimes delegates derive from it public delegate void EventHandler( object sender, EventArgs e); 57
  • 58. EventHandler – Example public class Button { public event EventHandler Click; public event EventHandler GotFocus; public event EventHandler TextChanged; … } public class ButtonTest { private static void Button_Click(object sender, EventArgs eventArgs) { Console.WriteLine("Call Button_Click() event"); } public static void Main() { Button button = new Button(); button.Click += Button_Click; } } 58
  • 60. Interfaces  Describe a group of methods (operations), properties and events  Can be implemented by given class or structure  Define only the methods’ prototypes  No concrete implementation  Can be used to define abstract data types  Can not be instantiated  Members do not have scope modifier and by default the scope is public 60
  • 61. Interfaces – Example public interface IPerson { string Name // property Name { get; set; } DateTime DateOfBirth // property DateOfBirth { get; set; } int Age // property Age (read-only) { get; set; } } 61
  • 62. Interfaces – Example (2) interface IShape { void SetPosition(int x, int y); int CalculateSurface(); } interface IMovable { void Move(int deltaX, int deltaY); } interface IResizable { void Resize(int weight); void Resize(int weightX, int weightY); void ResizeByX(int weightX); void ResizeByY(int weightY); } 62
  • 63. Interface Implementation  Classes and structures can implement (support) one or many interfaces  Interface realization must implement all its methods  If some methods do not have implementation the class or structure have to be declared as an abstract 63
  • 64. Interface Implementation – Example class Rectangle : IShape, IMovable { private int x, y, width, height; public void SetPosition(int x, int y) // IShape { this.x = x; this.y = y; } public int CalculateSurface() // IShape { return this.width * this.height; } public void Move(int deltaX, int deltaY) // IMovable { this.x += deltaX; this.y += deltaY; } } 64
  • 65. Abstract Classes  Abstract method is a method without implementation  Left empty to be implemented by some descendant class  When a class contains at least one abstract method, it is called abstract class  Mix between class and interface  Inheritors are obligated to implement their abstract methods  Can not be directly instantiated 65
  • 66. Abstract Class – Example abstract class MovableShape : IShape, IMovable { private int x, y; public void Move(int deltaX, int deltaY) { this.x += deltaX; this.y += deltaY; } public void SetPosition(int x, int y) { this.x = x; this.y = y; } public abstract int CalculateSurface(); } 66
  • 68. Cohesion  Cohesion describes how closely all the routines in a class or all the code in a routine support a central purpose  Cohesion must be strong  Classes must contain strongly related functionality and aim for single purpose  Cohesion is a useful tool for managing complexity  Well-defined abstractions keep cohesion strong 68
  • 69. Good and Bad Cohesion  Good cohesion: hard disk, CD-ROM, floppy  Bad cohesion: spaghetti code 69
  • 70. Strong Cohesion  Strong cohesion example  Class Math that has methods and constants:  Sin(), Cos(), Asin(), Sqrt(), Pow(), Exp()  Math.PI, Math.E double sideA = 40, sideB = 69; double angleAB = Math.PI / 3; double sideC = Math.Pow(sideA, 2) + Math.Pow(sideB, 2) - 2 * sideA * sideB * Math.Cos(angleAB); double sidesSqrtSum = Math.Sqrt(sideA) + Math.Sqrt(sideB) + Math.Sqrt(sideC); 70
  • 71. Bad Cohesion  Example of bad cohesion  Class Magic that has all these methods:  Another example: MagicClass.MakePizza("Fat Pepperoni"); MagicClass.WithdrawMoney("999e6"); MagicClass.OpenDBConnection(); public void PrintDocument(Document d); public void SendEmail(string recipient, string subject, string text); public void CalculateDistanceBetweenPoints(int x1, int y1, int x2, int y2) 71
  • 72. Coupling  Coupling describes how tightly a class or routine is related to other classes or routines  Coupling must be kept loose  Modules must depend little on each other  All classes and routines must have small, direct, visible, and flexible relations to other classes and routines  One module must be easily used by other modules 72
  • 73. Loose andTight Coupling  Loose Coupling:  Easily replace old HDD  Easily place this HDD to another motherboard  Tight Coupling:  Where is the video card?  Can you change the video card? 73
  • 74. Loose Coupling – Example class Report { public bool LoadFromFile(string fileName) {…} public bool SaveToFile(string fileName) {…} } class Printer { public static int Print(Report report) {…} } class LooseCouplingExample { static void Main() { Report myReport = new Report(); myReport.LoadFromFile("C:DailyReport.rep"); Printer.Print(myReport); } } 74
  • 75. Tight Coupling – Example class MathParams { public static double operand; public static double result; } class MathUtil { public static void Sqrt() { MathParams.result = CalcSqrt(MathParams.operand); } } class Example { static void Main() { MathParams.operand = 64; MathUtil.Sqrt(); Console.WriteLine(MathParams.result); } } 75
  • 76. Spaghetti Code  Combination of bad cohesion and tight coupling (spaghetti code): class Report { public void Print() {…} public void InitPrinter() {…} public void LoadPrinterDriver(string fileName) {…} public bool SaveReport(string fileName) {…} public void SetPrinter(string printer) {…} } class Printer { public void SetFileName() {…} public static bool LoadReport() {…} public static bool CheckReport() {…} } 76
  • 78. Inheritance  Inheritance is the ability of a class to implicitly gain all members from another class  Inheritance is fundamental concept in OOP  The class whose methods are inherited is called base (parent) class  The class that gains new functionality is called derived (child) class  Inheritance establishes an is-a relationship between classes: A is B 78
  • 79. Inheritance (2)  All class members are inherited  Fields, methods, properties, …  In C# classes could be inherited  The structures in C# could not be inherited  Inheritance allows creating deep inheritance hierarchies  In .NET there is no multiple inheritance, except when implementing interfaces 79
  • 80. How to Define Inheritance?  We must specify the name of the base class after the name of the derived  In the constructor of the derived class we use the keyword base to invoke the constructor of the base class public class Shape {...} public class Circle : Shape {...} public Circle (int x, int y) : base(x) {...} 80
  • 81. Inheritance – Example public class Mammal { private int age; public Mammal(int age) { this.age = age; } public int Age { get { return age; } set { age = value; } } public void Sleep() { Console.WriteLine("Shhh! I'm sleeping!"); } } 81
  • 82. Inheritance – Example (2) public class Dog : Mammal { private string breed; public Dog(int age, string breed): base(age) { this.breed = breed; } public string Breed { get { return breed; } set { breed = value; } } public void WagTail() { Console.WriteLine("Tail wagging..."); } } 82
  • 83. Inheritance – Example (3) static void Main() { // Create 5 years old mammal Mamal mamal = new Mamal(5); Console.WriteLine(mamal.Age); mamal.Sleep(); // Create a bulldog, 3 years old Dog dog = new Dog("Bulldog", 3); dog.Sleep(); dog.Age = 4; Console.WriteLine("Age: {0}", dog.Age); Console.WriteLine("Breed: {0}", dog.Breed); dog.WagTail(); } 83
  • 85. Polymorphism  Polymorphism is fundamental concept in OOP  The ability to handle the objects of a specific class as instances of its parent class and to call abstract functionality  Polymorphism allows creating hierarchies with more valuable logical structure  Allows invoking abstract functionality without caring how and where it is implemented 85
  • 86. Polymorphism (2)  Polymorphism is usually implemented through:  Virtual methods (virtual)  Abstract methods (abstract)  Methods from an interface (interface)  In C# to override virtual method the keyword override is used  C# allows hiding virtual methods in derived classes by the keyword new 86
  • 87. Polymorphism – Example class Person { public virtual void PrintName() { Console.WriteLine("I am a person."); } } class Trainer : Person { public override void PrintName() { Console.WriteLine("I am a trainer."); } } class Student : Person { public override void PrintName() { Console.WriteLine("I am a student."); } } 87
  • 88. Polymorphism – Example (2) static void Main() { Person[] persons = { new Person(), new Trainer(), new Student() }; foreach (Person p in persons) { Console.WriteLine(p); } // I am a person. // I am a trainer. // I am a student. } 88

Notas do Editor

  1. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  2. 3
  3. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  4. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  5. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  6. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  7. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  8. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  9. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  10. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  11. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  12. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  13. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  14. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  15. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  16. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  17. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  18. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  19. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  20. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  21. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  22. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  23. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  24. 29
  25. 30
  26. 31
  27. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  28. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  29. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  30. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  31. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  32. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  33. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  34. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  35. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  36. 43
  37. 44
  38. 45
  39. 46##
  40. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  41. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  42. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  43. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  44. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  45. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  46. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  47. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  48. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  49. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  50. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  51. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  52. 59##
  53. 67##
  54. 77##
  55. 78##
  56. 79##
  57. 84##
  58. 85##
  59. 87##
  60. 88##