Download as pdf or txt
Download as pdf or txt
You are on page 1of 25

Unit 3: Implementation of Object-Oriented Concept using C#

Object Oriented Programming Concepts in C#

Object Oriented Programming (OOP) is a programming model where programs are organized around
objects and data rather than action and logic.

OOP allows decomposition of a problem into a number of entities called objects and then builds data
and functions around these objects.

1. The software is divided into a number of small units called objects. The data and functions are
built around these objects.
2. The data of the objects can be accessed only by the functions associated with that object.
3. The functions of one object can access the functions of another object.

OOP has the following important features.

Class

A class is the core of any modern Object Oriented Programming language such as C#.

In OOP languages it is mandatory to create a class for representing data.

A class is a blueprint of an object that contains variables for storing data and functions to perform
operations on the data.

A class will not occupy any memory space and hence it is only a logical representation of data.

To create a class, you simply use the keyword "class" followed by the class name:

1. class Employee
2. {
3.
4. }

Object

Objects are the basic run-time entities of an object-oriented system. They may represent a person, a
place or any item that the program must handle.

"An object is a software bundle of related variable and methods."

"An object is an instance of a class"

Syntax to create an object of class Employee:

1. Employee objEmp = new Employee();

Abstraction
Page | 1
2. Abstraction is "To represent the essential feature without representing the background
details."

Abstraction lets you focus on what the object does instead of how it does it.

Abstraction provides you a generalized view of your classes or objects by providing relevant
information.

Abstraction is the process of hiding the working style of an object, and showing the
information of an object in an understandable manner.

Encapsulation

Wrapping up a data member and a method together into a single unit (in other words class) is called
Encapsulation.

Encapsulation is like enclosing in a capsule. That is enclosing the related operations and data related
to an object into that object.

Encapsulation is like your bag in which you can keep your pen, book etcetera. It means this is the
property of encapsulating members and functions.

1. class Bag {
2. book;
3. pen;
4. ReadBook();
5. }

Encapsulation means hiding the internal details of an object, in other words how an object does
something.

Inheritance

When a class includes a property of another class it is known as inheritance.

Inheritance is a process of object reusability.For example, a child includes the properties of its
parents.

1. public class ParentClass {


2. public ParentClass() {
3. Console.WriteLine("Parent Constructor.");
4. }
5. public void print() {
6. Console.WriteLine("I'm a Parent Class.");
7. }
8. }
9. public class ChildClass: ParentClass {
10. public ChildClass() {
11. Console.WriteLine("Child Constructor.");
12. }
13. public static void Main() {
14. ChildClass child = new ChildClass();
15. child.print();
16. }
17. }

INDEXER IN C#:
Page | 2
In c# introduce new concept is Indexer. This is very useful for some situation. Let as discuss something
about Indexer.

• Indexer Concept is object act as an array.


• Indexer an object to be indexed in the same way as an array.
• Indexer modifier can be private, public, protected or internal.
• The return type can be any valid C# types.
• Indexers in C# must have at least one parameter. Else the compiler will generate a compilation
error.

this [Parameter]
{
get
{
// Get codes goes here
}
set
{
// Set codes goes here
}
}

For Example:

using System;
using System.Collections.Generic;
using System.Text;

namespace Indexers
{
class ParentClass
{
private string[] range = new string[5];
public string this[int indexrange]
{
get
{
return range[indexrange];
}
set
{
range[indexrange] = value;
}
}
}

/* The Above Class just act as array declaration using this pointer */

class childclass
{
public static void Main()
{
ParentClass obj = new ParentClass();

/* The Above Class ParentClass create one object name is obj */

obj[0] = "ONE";
obj[1] = "TWO";
Page | 3
obj[2] = "THREE";
obj[3] = "FOUR ";
obj[4] = "FIVE";
Console.WriteLine("WELCOME TO C# CORNER HOME PAGE\n");
Console.WriteLine("\n");

Console.WriteLine("{0}\n,{1}\n,{2}\n,{3}\n,{4}\n", obj[0], obj[1], obj[2], obj[3], obj[4]);


Console.WriteLine("\n");
Console.WriteLine("ALS.Senthur Ganesh Ram Kumar\n");
Console.WriteLine("\n");
Console.ReadLine();
}
}
}

C# Properties
C# Properites doesn't have storage location. C# Properites are extension of fields and accessed
like fields.

The Properties have accessors that are used to set, get or compute their values.

Usage of C# Properties

C# Properties can be read-only or write-only.


We can have logic while setting values in the C# Properties.
We make fields of the class private, so that fields can't be accessed from outside the class
directly. Now we are forced to use C# properties for setting or getting values.

Example 1:

using System;
public class Employee
{
private string name;

public string Name


{
get
{
return name;
}
set
{
name = value;
}
}
}
class TestEmployee{
public static void Main(string[] args)
{
Employee e1 = new Employee();

Page | 4
e1.Name = "Sonoo Jaiswal";
Console.WriteLine("Employee Name: " + e1.Name);

}
}

Example 2:
using System;
class Example
{
int _number;
public int Number
{
get
{
return this._number;
}
set
{
this._number =value;
}
}
}
class Program
{
static void Main()
{
Example example = new Example();
example.Number = 5; // set { }
Console.WriteLine(example.Number); // get
{}
}
}

Constructor & Destructor


A special method of the class that will be automatically invoked when an instance of the class is created is
called a constructor. The main use of constructors is to initialize private fields of the class while creating
an instance for the class. When you have not created a constructor in the class, the compiler will
automatically create a default constructor in the class. The default constructor initializes all numeric fields
in the class to zero and all string and object fields to null.

Some of the key points regarding the Constructor are:

• A class can have any number of constructors.


• A constructor doesn't have any return type, not even void.
• A static constructor can not be a parametrized constructor.
• Within a class you can create only one static constructor.

Constructors can be divided into 5 types:

Page | 5
1. Default Constructor
2. Parametrized Constructor
3. Copy Constructor

Default Constructor

A constructor without having any parameters called default constructor. In this constructor every instance
of the class will be initialized without any parameter values like as shown below

using System;
namespace ConsoleApplication3
{
class Sample
{
public string param1, param2;
public Sample() // Default Constructor
{
param1 = "Welcome";
param2 = "to ASP.NET";
}
}
class Program
{
static void Main(string[] args)
{
Sample obj=new Sample(); // Once object of class created automatically constructor will be called
Console.WriteLine(obj.param1);
Console.WriteLine(obj.param2);
Console.ReadLine();
}
}
}
When we run above program it will show output like as shown below

Output

Welcome
to ASP.NET

Parameterized Constructors

A constructor with at least one parameter is called as parameterized constructor. In parameterized


constructor we can initialize each instance of the class to different values like as shown below

using System;
namespace ConsoleApplication3
{
class Sample
{
public string param1, param2;
public Sample(string x, string y) // Declaring Parameterized constructor with Parameters
{
param1 = x;
Page | 6
param2 = y;
}
}
class Program
{
static void Main(string[] args)
{
Sample obj=new Sample("Welcome","Aspdotnet-Suresh"); // Parameterized Constructor Called
Console.WriteLine(obj.param1 +" to "+ obj.param2);
Console.ReadLine();
}
}
}
When we run above program it will show output like as shown below

Output

Welcome to Aspdotnet-Suresh

Constructor Overloading

In c# we can overload constructor by creating another constructor with same method name and different
parameters like as shown below

using System;
namespace ConsoleApplication3
{
class Sample
{
public string param1, param2;

public Sample() // Default Constructor


{
param1 = "Hi";
param2 = "I am Default Constructor";
}
public Sample(string x, string y) // Declaring Parameterized constructor with Parameters
{
param1 = x;
param2 = y;
}
}
class Program
{
static void Main(string[] args)
{
Sample obj = new Sample(); // Default Constructor will Called
Sample obj1=new Sample("Welcome","Aspdotnet-Suresh"); // Parameterized Constructor will Called
Console.WriteLine(obj.param1 + ", "+obj.param2);
Console.WriteLine(obj1.param1 +" to " + obj1.param2);
Console.ReadLine();
}
}

Page | 7
When we run above program it will show output like as shown below

Output

Hi, I am Default Constructor


Welcome to Aspdotnet-Suresh

Copy Constructor

A parameterized constructor that contains a parameter of same class type is called as copy constructor.
Main purpose of copy constructor is to initialize new instance to the values of an existing instance. Check
below example for this

using System;
namespace ConsoleApplication3
{
class Sample
{
public string param1, param2;
public Sample(string x, string y)
{
param1 = x;
param2 = y;
}
public Sample(Sample obj) // Copy Constructor
{
param1 = obj.param1;
param2 = obj.param2;
}
}
class Program
{
static void Main(string[] args)
{
Sample obj = new Sample("Welcome", "Aspdotnet-Suresh"); // Create instance to class Sample
Sample obj1=new Sample(obj); // Here obj details will copied to obj1
Console.WriteLine(obj1.param1 +" to " + obj1.param2);
Console.ReadLine();
}
}
}
When we run above program it will show output like as shown below

Output

Welcome to Aspdotnet-Suresh

Page | 8
Destructor in C#
Destructors are used to destruct instances of classes. In this article you will understand how different C#
destructors are when compared to C++ destructors.

In C# you can never call them, the reason is one cannot destroy an object. So who has the control over
the destructor (in C#)? it's the .NET frameworks Garbage Collector (GC).

Syntax of Destructor(~)

~ ClassName()

using System;
namespace destructorex
{
class Program
{
~Program() // destructor define
{
// clean up statement
}
}
}

Characteristics of Destructor
• Destructors (~) cannot be defined in Structs.
• Destructors (~) are only used with classes.
• Destructor cannot be inherited or overloaded.
• Destructor does not take modifiers or have parameters.
• Destructor cannot be called. They are invoked automatically.
• An instance becomes eligible for destruction when it is no longer possible for any code to use the
instance.
• The Programmer has no control over when destructor is called because this is determined by
Garbage Collector.
• Destructor is called when program exits.

Working with "static" Members

Static Variables and Static Methods

Each object has its own set of member variables and all the member variables have a scope.

If we want a variable to have the same value throughout all instances of the object then we can
declare it as a static variable in our program. To manipulate and use the values of static variables we
can also define a function as static.

The keyword "static" means that only one instance of a given variable exists for a class. Static
variables are used to define constants because their values can be retrieved by invoking the class
without creating an instance of it.

Static variables can be initialized outside the member function or class definition. The following code
is an example of a static variable, which shows the declaration and initialization of a static variable.

Page | 9
using System;
namespace staticexample
{
class Program
{
public static int i;
public static void display()
{
i=10;
Console.WriteLine(i);
}
public void demo()
{
int j=20;
Console.WriteLine(j);
}

static void Main(string[] args)


{
Program obj = new Program();
Program.display();
obj.demo();
Console.Read();
}
}
}

Inheritance & Polymorphism

Types of Inheritance
Acquiring (taking) the properties of one class into another class is called inheritance. Inheritance
provides reusability by allowing us to extend an existing class.

The reason behind OOP programming is to promote the reusability of code and to reduce complexity
in code and it is possible by using inheritance.

The following are the types of inheritance in C#.

1. Single inheritance
In this inheritance, a derived class is created from a single base class.

Page | 10
//Base Class
class A
{
public void fooA()
{
//TO DO:
}
}

//Derived Class
class B : A
{
public void fooB()
{
//TO DO:
}
}

2. Multi-level inheritance
In this inheritance, a derived class is created from another derived class.

//Base Class
class A
{
public void fooA()
{
//TO DO:
}
}

//Derived Class
class B : A
{
public void fooB()
{
//TO DO:

Page | 11
}
}

//Derived Class
class C : B
{
public void fooC()
{
//TO DO:
}
}

3. Hierarchical inheritance
In this inheritance, more than one derived classes are created from a single base.

//Base Class
class A
{
public void fooA()

{
//TO DO:
}
}

//Derived Class
class B : A
{
public void fooB()
{
//TO DO:
}
}

//Derived Class
class C : A
{
public void fooC()
{
//TO DO:
}
}

//Derived Class
class D : C
Page | 12
{
public void fooD()
{
//TO DO:
}
}

//Derived Class
class E : C
{
public void fooE()
{
//TO DO:
}
}

//Derived Class
class F : B
{
public void fooF()
{
//TO DO:
}
}

//Derived Class
class G :B
{
public void fooG()
{
//TO DO:
}
}

4. Hybrid inheritance
This is combination of more than one inheritance. Hence, it may be a combination of Multilevel and
Multiple inheritance or Hierarchical and Multilevel inheritance or Hierarchical and Multipath inheritance
or Hierarchical, Multilevel and Multiple inheritance.
Since .NET Languages like C#, F# etc. does not support multiple and multipath inheritance. Hence
hybrid inheritance with a combination of multiple or multipath inheritance is not supported by .NET
Languages.

//Base Class
class A
{
public void fooA()
{

Page | 13
//TO DO:
}
}

//Base Class
class F
{
public void fooF()
{
//TO DO:
}
}

//Derived Class
class B : A, F
{
public void fooB()
{
//TO DO:
}
}

//Derived Class
class C : A
{
public void fooC()
{
//TO DO:
}
}

//Derived Class
class D : C
{
public void fooD()
{
//TO DO:
}
}

//Derived Class
class E : C
{
public void fooE()
{
//TO DO:
}
}

Constructor in Inheritance

Unlike the above class behaviour, constructors that are declared within a base class are not inherited
by subclasses. As with any other class, a subclass with no constructors defined is provided with a

Page | 14
default constructor that provides no explicit functionality. The constructors from the base class are
not made available when creating new subclass object instances.
When a subclass is instantiated, the standard behaviour is for the default constructor of the base
class to be called automatically. In this way, the base constructor can initialise the base class before
the subclass's constructor is executed.

class Program
{
static void Main()
{
MySubclass test = new MySubclass();
}
}

class MyBaseClass
{
public MyBaseClass()
{
Console.WriteLine("MyBaseClass constructor called.");
}
}

class MySubclass : MyBaseClass


{
public MySubclass()
{
Console.WriteLine("MySubclass constructor called.");
}
}

Interface Implementation

An interface is defined as a syntactical contract that all the classes inheriting the interface should
follow. The interface defines the 'what' part of the syntactical contract and the deriving classes define
the 'how' part of the syntactical contract.
Interfaces define properties, methods, and events, which are the members of the interface.
Interfaces contain only the declaration of the members. It is the responsibility of the deriving class to
define the members. It often helps in providing a standard structure that the deriving classes would
follow.
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System;

namespace InterfaceApplication {

public interface ITransactions {


// interface members
void showTransaction();
double getAmount();
}

Page | 15
public class Transaction : ITransactions {
private string tCode;
private string date;
private double amount;

public Transaction() {
tCode = " ";
date = " ";
amount = 0.0;
}

public Transaction(string c, string d, double a) {


tCode = c;
date = d;
amount = a;
}

public double getAmount() {


return amount;
}

public void showTransaction() {


Console.WriteLine("Transaction: {0}", tCode);
Console.WriteLine("Date: {0}", date);
Console.WriteLine("Amount: {0}", getAmount());
}
}

class Tester {

static void Main(string[] args) {


Transaction t1 = new Transaction("001", "8/10/2012", 78900.00);
Transaction t2 = new Transaction("002", "9/10/2012", 451900.00);
t1.showTransaction();
t2.showTransaction();
Console.ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following result −
Transaction: 001
Date: 8/10/2012
Amount: 78900
Transaction: 002
Date: 9/10/2012
Amount: 451900

Operator and method Overloading and overriding


Operator Overloading
You can redefine or overload most of the built-in operators available in C#. Thus a programmer can
use operators with user-defined types as well. Overloaded operators are functions with special names
the keyword operatorfollowed by the symbol for the operator being defined. similar to any other
function, an overloaded operator has a return type and a parameter list.

Page | 16
Operators Overloadability
+, -, *, /, %, &, |,
All C# binary operators can be overloaded.
<<, >>
+, -, !, ~, ++, --,
All C# unary operators can be overloaded.
true, false
==, !=, <, >, <= ,
All relational operators can be overloaded, but only as pairs.
>=
&&, || They can't be overloaded.
[] (Array index
They can't be overloaded.
operator)
() (Conversion
They can't be overloaded.
operator)
These compound assignment operators can be overloaded. But in C#, these
+=, -=, *=, /=, %= operators are automatically overloaded when the respective binary operator is
overloaded.
=, . , ?:, ->, new,
These operators can't be overloaded in C#.
is, as, sizeof

Overloading Unary Operators

The general form of operator function for unary operators is as follows.

public static return_type operator op (Type t)


{
// Statements
}

Where Type must be a class or struct.

The return type can be any type except void for unary operators like +, ~, ! and dot (.) but the
return type must be the type of 'Type' for ++ and - operators and must be a bool type for true and
false operators. Also remember that the true and false operators can be overloaded only as pairs.
The compilation error occurs if a class declares one of these operators without declaring the other.

The following program overloads the unary - operator inside the class Complex

// Unary operator overloading

using System;
class Complex
{
private int x;
private int y;
public Complex()
{
}
public Complex(int i, int j)
{
x = i;
y = j;
}
public void ShowXY()
{
Page | 17
Console.WriteLine("{0} {1}",x,y);
}
public static Complex operator -(Complex c)
{
Complex temp = new Complex();
temp.x = -c.x;
temp.y = -c.y;
return temp;
}
}
class MyClient
{
public static void Main()
{
Complex c1 = new Complex(10,20);
c1.ShowXY(); // displays 10 & 20
Complex c2 = new Complex();
c2.ShowXY(); // displays 0 & 0
c2 = -c1;
c2.ShowXY(); // diapls -10 & -20
}
}

Overloading Binary Operators

An overloaded binary operator must take two arguments; at least one of them must be of the type
class or struct, in which the operation is defined. But overloaded binary operators can return any
value except the type void. The general form of an overloaded binary operator is as follows.

public static return_type operator op (Type1 t1, Type2 t2)


{
//Statements
}

A concrete example is given below.

// Binary operator overloading


// Author: rajeshvs@msn.com
using System;
class Complex
{
private int x;
private int y;
public Complex()
{}
public Complex(int i, int j)
{
x = i;
y = j;
}
public void ShowXY()
{
Console.WriteLine("{0} {1}",x,y);
}
public static Complex operator +(Complex c1,Complex c2)
{
Complex temp = new Complex();
temp.x = c1.x+c2.x;
Page | 18
temp.y = c1.y+c2.y;
return temp;
}
}
class MyClient
{
public static void Main()
{
Complex c1 = new Complex(10,20);
c1.ShowXY(); // displays 10 & 20
Complex c2 = new Complex(20,30);
c2.ShowXY(); // displays 20 & 30
Complex c3 = new Complex();
c3 = c1 + c2;
c3.ShowXY(); // dislplays 30 & 50
}
}

Function Overloading
In function overloading, a function works differently based on parameters. A single
function can have different nature based on number of parameters and types of
parameters. For example, you have a function Sum() that accepts values as parameter
and print their addition. You can write multiple function with name Sum() but the
parameter signature must be different.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Function_Overloading
{
class Program
{
static void Main(string[] args)
{
Calculator.sum();
Calculator.sum(5,4);
Calculator.sum(9.3f, 8.6f);
Calculator.sum("Hello World");
Console.Read();
}
}
static class Calculator
{
public static void sum()
{
Console.WriteLine("No Value Provided");

Page | 19
}
public static void sum(int x, int y)
{
Console.WriteLine("Sum of {0} and {1} is {2}", x, y, (x + y));
}
public static void sum(float x, float y)
{
Console.WriteLine("Sum of {0} and {1} is {2}", x, y, (x + y));
}
public static void sum(string s)
{
Console.WriteLine("{0} - is not a numeric value", s);
}
}
}

Method Overriding
If derived class defines same method as defined in its base class, it is known as method overriding in C#.
It is used to achieve runtime polymorphism. It enables you to provide specific implementation of the
method which is already provided by its base class.

To perform method overriding in C#, you need to use virtual keyword with base class method
and override keyword with derived class method.

using System;
public class Animal{
public virtual void eat(){
Console.WriteLine("Eating...");
}
}
public class Dog: Animal
{
public override void eat()
{
Console.WriteLine("Eating bread...");
}
}
public class TestOverriding
{
public static void Main()
{
Dog d = new Dog();
d.eat();
}
}

Static Binding and Dynamic Binding


Connecting a method call to the method body is known as binding.

There are two types of binding

Page | 20
1. static binding (also known as early binding).

2. dynamic binding (also known as late binding).

static binding
When type of the object is determined at compiled time(by the compiler), it is known as static binding.

If there is any private, final or static method in a class, there is static binding.

Example of static binding


class Dog{
private void eat(){System.out.println("dog is eating...");}

public static void main(String args[]){


Dog d1=new Dog();
d1.eat();
}
}

Dynamic binding
When type of the object is determined at run-time, it is known as dynamic binding.

Example of dynamic binding


class Animal{
void eat(){System.out.println("animal is eating...");}
}

class Dog extends Animal{


void eat(){System.out.println("dog is eating...");}

public static void main(String args[]){


Animal a=new Dog();
a.eat();
}
}

Virtual

A virtual method can be redefined. The virtual keyword designates a method that is overridden in
derived classes. We can add derived types without modifying the rest of the program. The runtime
type of objects thus determines behavior.
using System;
Page | 21
class A
{
public virtual void Test()
{ Console.WriteLine("A.Test");
}
}

class B : A
{
public override void Test()
{ Console.WriteLine("B.Test");
}
}

class Program
{
static void Main()
{
A ref1 = new A();
ref1.Test();
A ref2 = new B();
ref2.Test();
}
}

Abstract class
If a class is defined as abstract then we can't create an instance of that class. By the creation of the
derived class object where an abstract class is inherit from, we can call the method of the abstract
class.

Let's take an example: First of all, select a console application as follows:

1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Text;
5. namespace ConsoleApplication13 {
6. abstract class mcn {
7. public int add(int a, int b) {
8. return (a + b);
9. }
10. }
11. class mcn1: mcn {
12. public int mul(int a, int b) {
13. return a * b;
14. }
15. }
16. class test {
17. static void Main(string[] args) {
18. mcn1 ob = new mcn1();
19. int result = ob.add(5, 10);
20. Console.WriteLine("the result is {0}", result);
Page | 22
21. }
22. }
23. }

Sealed Class

Sealed class is used to define the inheritance level of a class.

The sealed modifier is used to prevent derivation from a class. An error occurs if a sealed class is specified
as the base class of another class.

class Program

static void Main(string[] args)

B b = new B();

b.print_B();

A a = new A();

a.printA();

Console.ReadLine();

sealed class A

private int x = 1;

public void printA()

Console.WriteLine(x);

Page | 23
}

class B

public void print_B()

A a = new A();

a.printA();

Sealed Methods
Sealed method is used to define the overriding level of a virtual method.

Sealed keyword is always used with override keyword.

namespace ConsoleApplication2

class A

virtual public void printA()

Console.WriteLine("In class A");

class B : A

sealed override public void printA()

Page | 24
Console.WriteLine("In class B");

class C : B

override public void printA() //Error: cannot override inherited member

{ //B.printA() because it is sealed.

Page | 25

You might also like