Session
2
Implementing OOP
concepts in C#
Review
C# is an object oriented language with many powerful
features and is an integral part of the .Net platform
Variables in C# are declared in the following way
AccessModifier DataType VariableName;
C# provides the if and switchcase constructs to
perform operations based on the value of an expression.
C# provides the following types of iteration constructs,
while loop
do loop
for loop
foreach loop
In C#, the data types are divided into two fundamental
categories namely value types and reference types.
C# Simplified / Session 2 / 2 of 28
Review Contd
Boxing is the conversion of a value type into a
reference type while Unboxing refers to
converting a reference type into a value type.
Structs in C# can have methods defined within
them, and represent Value types.
Enums (short for Enumerators) are a set of
named numeric constants.
C# programs can be written using the Visual
Studio .NET IDE as well as Notepad
C# Simplified / Session 2 / 3 of 28
Objectives
Use Constructors In C#
Use Destructors In C#
Explain the working of Garbage Collector
Discuss Method Overloading
Discuss Operator Overloading
Use Inheritance in C#
Discuss Overriding
C# Simplified / Session 2 / 4 of 28
Constructors In C#
Are special types of methods in a class
Are called every time an object is
created
Are generally used for initialization
Have the same name as the class
Return no value
C# Simplified / Session 2 / 5 of 28
Constructors - Example
using System;
public class DaysInYear
{
private int days;
public DaysInYear()
{
days = 365;
}
static void Main(String[] args)
{
DaysInYear newDaysInYear =new DaysInYear();
[Link] ([Link]);
}
}
With Constructor
Without Constructor
C# Simplified / Session 2 / 6 of 28
Parameterized
Constructors
public class DaysInYear
{
private int days;
public DaysInYear()
{
days = 365;
}
public DaysInYear(int day)
{
days = day;
}
public DaysInYear(String dayOne)
{
days =Convert.ToInt32(dayOne);
}
public void setDay(int newDays)
{
days = newDays;
}
Pass different number
of arguments
(or)
Pass the same number
of arguments but of
different types
C# Simplified / Session 2 / 7 of 28
Destructors In C#
Do not take any parameters
Declaration is same as constructors but
preceded with a ~
Called by the Garbage Collector in C#
The Garbage Collector frees memory by
destroying objects that are no longer required
or referenced
Syntax - ~DaysInYear()
{
//Destructor Implementation
}
C# Simplified / Session 2 / 8 of 28
Garbage Collector
Working of a garbage collector:
When an object that has a destructor defined, is allocated
memory, the runtime adds this object to a list of objects
that require destruction (or finalization)
Periodically, the Garbage Collector checks for objects that
have no references
If an object whose name does not appear in the finalizer
list is found, then the object is cleared up instantly
The runtime refers to the destructor as a finalizer, but in
C#, it is called as a destructor
When garbage collection is complete, the finalizer thread is
called, which calls the finalizer methods (destructors) of all
objects, marked as ready for finalization
C# Simplified / Session 2 / 9 of 28
Garbage Collector
Contd
After the finalization of an object has occurred, it is
removed from the list of objects that require finalization
Since the object is neither on the finalizer list nor
referenced, it gets cleared up when garbage collection
takes place the next time
Objects with destructors take up more resources as they
stay for a longer period of time in memory even when
they are not required
Finalization takes place as a separate thread, utilizing
the resources to a great extent
C# Simplified / Session 2 / 10 of 28
Method Overloading
Two ways of overloading methods
By specifying different number of
parameters
By specifying different types of
parameters
C# Simplified / Session 2 / 11 of 28
Method Overloading - Different
number of parameters
using System;
public class Area
{
private int areaVal;
public void AreaCal(int radius)
{
areaVal = (22/7)* radius*radius;
}
public void AreaCal(int length, int
breadth)
{
areaVal = length*breadth;
}
public void AreaCal(int length, int
breadth, int height)
{
areaVal = length*breadth*height;
}
C# Simplified / Session 2 / 12 of 28
Method Overloading Different types of parameters
...
public void Add(int number1, int number2)
{
sum = number1 + number2;
}
public void Add(string value1, string value2)
{
int sum;
sum = [Link](value1) + [Link](value2);
[Link] ("Sum is {0}",sum);
[Link] ("Strings are converted to integers to
add);
}
...
C# Simplified / Session 2 / 13 of 28
Operator Overloading
Contd
Overloading an operator means making
it
behave differently from its normal
behaviour //line 1
int result = [Link](54, 200);
//line 2
int result2 = 54 + 200;
Operators are used to make equations look
simple and easy to understand
List of operators that can be overloaded
C# Simplified / Session 2 / 14 of 28
Operator Overloading
using System;
public class Distance
{
int longitude, latitude;
public Distance()
{
longitude = 0;
latitude = 0;
}
public Distance(int longitude, int latitude)
{
[Link] = longitude;
[Link] = latitude;
}
public static Distance operator - (Distance
first, Distance second)
{
return new
Distance([Link] [Link], [Link] [Link]);
}
//main
}
public static void Main()
{
Distance start = new Distance();
Distance objDistance = new Distance();
Distance finish = new Distance();
[Link] = 12;
This statement does
[Link] = 10;
not return an error as
[Link] = 2;
the - operator is
[Link] = 1;
overloaded
objDistance = start - finish;
[Link] ("The Finish is {0}
Degrees East and {1} Degrees North of the Start.",
[Link],[Link]);
}
C# Simplified / Session 2 / 15 of 28
Inheritance In C#
Declare and use a new class as a descendant
of another class
Saves trouble of re-writing code
Provides luxury of code re-use
The class from which the other classes can
inherit is called base class
Two types of Inheritance
Single Inheritance
Multiple Inheritance
C# Simplified / Session 2 / 16 of 28
Single Inheritance
using System;
namespace Ch2Ex5
{
class Inherit
{
static void Main(string[] args)
{
Square squareObj =new Square();
Rectangle rectObj =new
Rectangle();
[Link](10,20);
[Link](20,20);
}
}
class Shape
{
public int length;
public int breadth;
public void calculateArea(int len,
int
breadth);
{
}
}
class Rectangle:Shape
{
public Rectangle()
{
length=0;
breadth=0;
}
class Rectangle:Shape
{
public Rectangle()
{
length=0;
breadth=0;
}
public void calculateArea(int len, int
breadth)
{
[Link] ("Area of a Rectangle
is
{0}",len*breadth);
}
C# Simplified / Session 2 / 17 of 28
Single Inheritance
Contd
class Square:Shape
{
public Square()
{
}
public void calculateArea(int side1, int
side2)
{
int area;
area = side1*side2;
[Link] ("Area of a Square is
{0}",area);
}
}
}
C# Simplified / Session 2 / 18 of 28
Sealing a Class
A class is sealed when no class
should be allowed to inherit from
that class.
Keyword sealed is used to seal a
class classOne
class. sealed
{
//Class Implementation
}
C# Simplified / Session 2 / 19 of 28
base Keyword
Used to access the members of a
base class from within a derived class
Used to call constructors of a base
class while creating an instance of a
derived class
Using the keyword base in a static
method will result in an error
C# Simplified / Session 2 / 20 of 28
override keyword
Used to modify a method
An override method provides a new
implementation of the base method. The
base method should be declared as virtual
Accessibility level of a base method cannot
be changed by a method overriding it
Keywords new, static, virtual cannot be used
along with override modifier
C# Simplified / Session 2 / 21 of 28
virtual keyword
Keyword virtual is used in the definition of a
method to support polymorphism
Used to modify method declaration in a
class
Child classes are free to implement their
own versions of virtual method using
override keyword
Virtual modifier cannot be used with
modifiers like static and override
C# Simplified / Session 2 / 22 of 28
Virtual keyword Contd
Syntax for declaring a virtual method
[access modifier] virtual [return-type]
name( [parameters-list] )
{
//virtual method implementation
}
C# Simplified / Session 2 / 23 of 28
new keyword
Used as an operator or as a modifier
new modifier is used to explicitly
hide a member that is inherited from
the base class
It is an error to use both new and
override on the same method
C# Simplified / Session 2 / 24 of 28
New keyword Contd
using System;
public class Base
{
public static int val = 123;
}
public class Derv : Base
{
//new modifier required
public static int val = 456;
public static void Main()
{
//will execute derived class variable
[Link] (val);
}
}
C# Simplified / Session 2 / 25 of 28
Method Overriding
To override an existing method of the
base class:
Declare a new method in the inherited
class with the same name
Prefix it with the new keyword
C# Simplified / Session 2 / 26 of 28
Method Overriding Example
class MethodOverride
{
public static void Main()
{
StringAddition objStringAddition = new
StringAddition();
[Link]();
}
}
using System;
class IntAddition
{
public void add()
{
int firstNum =1;
int secondNum =2;
[Link] ("The Sum of the two numbers is :
{0}", firstNum+secondNum);
}
}
class StringAddition : IntAddition
{
new public void add()
{
string firstStr="a";
string secondStr="b";
[Link] ("The Sum of the two strings is :
{0}", firstStr+secondStr);
}
}
C# Simplified / Session 2 / 27 of 28
Summar
y
Parameterised constructors are constructors that take in parameters.
Constructors can be differentiated during run-time based on the
number of arguments or the type of the arguments passed.
In C#, the destructor is called by Garbage Collector.
Methods can be overloaded in C# in any of the two ways.
By specifying different number of parameters
By specifying different type of parameters
C# allows us to overload operators.
Overloading an operator means making an operator (for example, the
addition operator, +) behave differently when applied on certain
object of classes or structs.
C# does not support multiple inheritances.
To override an existing method of the base class, we declare a new
method in the inherited class of the same name and prefix it with the
new keyword.
C# Simplified / Session 2 / 28 of 28