0% found this document useful (0 votes)
22 views

UNIT-3 Pillars of OOP Object Oriented Programming: Prof - Dharesh Kumatagi, Chetana Bca College, Vijayapur

The document discusses the three main pillars of object-oriented programming: encapsulation, inheritance, and polymorphism. It provides examples and explanations of each pillar, including different types of inheritance such as single, multi-level, and multiple inheritance (through interfaces in C#). Method overloading and overriding are discussed as examples of static and dynamic polymorphism.

Uploaded by

Adesh K
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

UNIT-3 Pillars of OOP Object Oriented Programming: Prof - Dharesh Kumatagi, Chetana Bca College, Vijayapur

The document discusses the three main pillars of object-oriented programming: encapsulation, inheritance, and polymorphism. It provides examples and explanations of each pillar, including different types of inheritance such as single, multi-level, and multiple inheritance (through interfaces in C#). Method overloading and overriding are discussed as examples of static and dynamic polymorphism.

Uploaded by

Adesh K
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

C# AND .

NET FRAMEWORK BCA III SEMESTER

UNIT-3
Pillars of OOP
Object Oriented Programming

A programming model which is mainly organized around the objects is called Object
Oriented Programming or the Programming where the main focus of programmer while
modelling any problem is objects. (The name OOP indicates the same).
3 core principals of oops are
1. Encapsulation
2. Inheritance
3. Polymorphism.

Encapsulation is defined as wrapping up of data and information under a single unit. In


object-oriented programming, Encapsulation is defined as binding together the data and
the functions that manipulate them. It is an ability to hide internal details of an object
from its user.it is not possible to change state of an object directly. We can restrict the
access of the variables by switching the access-modifier.

Example:

Public Class Account


{
private double balance;
public double GetBalance()
{
return balance;
}
}
//Imagine main as outside world
public static void Main()
{
Account obj=new Account();
double currentBalance=obj.GetBalance();

//Following thing is not possible since that data member is private


obj.balance=20000000000;
}

Inheritance

Inheritance is a technique of acquiring the properties of another class having features in


common. It allows us to increase the reusability and reduce the duplication of code. It is
also known as a child-parent relationship, where a child inherits the properties of its
parent. It increases integrity of program and productivity of programmer.

There are 3 types of Inheritance,

Single Inheritance
Multi-level Inheritance
Multiple Inheritance

PROF.DHARESH KUMATAGI, CHETANA BCA COLLEGE, VIJAYAPUR 1


C# AND .NET FRAMEWORK BCA III SEMESTER

Single Inheritance

When a single derived class inherits properties from a single base class is called single
inheritance.
Class A
{
//data members;
//member functions;
}
Class B:A
{
//data members;
//member functions;
}

Example:
using System;
public class Employee
{
public float salary = 40000;
}
public class Programmer: Employee
{
public float bonus = 10000;
}
class TestInheritance{
public static void Main(string[] args)
{
Programmer p1 = new Programmer();
Console.WriteLine("Salary: " + p1.salary);
Console.WriteLine("Bonus: " + p1.bonus);
Console.WriteLine (“Total Salary:”, p1.salary+p1.bonus);

}
}

Salary: 40000
Bonus: 10000
Total Salary:50000

Multi-level Inheritance

In multi-level inheritance, a derived class inherits from a base class and then the same
derived class becomes a base class for another derived class. The properties of one class
are inherited to different levels.

PROF.DHARESH KUMATAGI, CHETANA BCA COLLEGE, VIJAYAPUR 2


C# AND .NET FRAMEWORK BCA III SEMESTER

Class A
{
//data members;
//member functions;
}
Class B:A
{
//data members;
//member functions;
}
Class C:B
{
//data members;
//member functions;
}

In above syntax class B inherits properties of its parent class A. Class B is child class of
class A. Class C is child class of class B and it inherits all the properties of class B. Indirectly
class C is inheriting properties of class A through class B.

Example:

using System;
public class Employee
{
public float salary = 40000;
}
public class Programmer: Employee
{
public float bonus = 10000;
}
public class SeniorProgrammer: Programmer
{
public float extrabonus = 500;
}
class TestInheritance{
public static void Main(string[] args)
{
SeniorProgrammer p1 = new SeniorProgrammer ();
Console.WriteLine("Salary: " + p1.salary);
Console.WriteLine("Bonus: " + p1.bonus);
Console.WriteLine("ExtraBonus: " + p1.extrabonus);
Console.WriteLine (“Total Salary:”, p1.salary+p1.bonus+p1.extrabonus);

}
}

Salary: 40000
Bonus: 10000
ExtraBonus: 500
Total Salary:50500
Multiple inheritance

PROF.DHARESH KUMATAGI, CHETANA BCA COLLEGE, VIJAYAPUR 3


C# AND .NET FRAMEWORK BCA III SEMESTER

Multiple inheritance

In multiple inheritance, a single derived class inherits from multiple base classes. C#
doesn't support multiple inheritance. However, we can achieve multiple inheritance
through interfaces.

interface A
{
//data members;
//member functions;
}
interface B
{
//data members;
//member functions;
}
Class C:A,B
{
//data members;
//member functions;
}
using System;
namespace MathOperations
{
interface calc1
{
int add(int a, int b);
}
interface calc2
{
int sub(int x, int y);
}
class Calculation : calc1, calc2
{
public int result1;
public int add(int a, int b)
{
return result1 = a + b;
}
public int result2;
public int sub(int x, int y)
{
return result2 = x - y;
}
class Program
{
static void Main(string[] args)
{
Calculation c = new Calculation();
c.add(8, 2);
c.sub(20, 10);
Console.WriteLine("Multiple Inheritance concept Using Interfaces :\n ");
Console.WriteLine("Addition: " + c.result1);
Console.WriteLine("Substraction: " + c.result2);
Console.ReadKey();
}

PROF.DHARESH KUMATAGI, CHETANA BCA COLLEGE, VIJAYAPUR 4


C# AND .NET FRAMEWORK BCA III SEMESTER

}
}
}

Polymorphism
Polymorphism is a Greek word, meaning "one name many forms". In other words,
one object has many forms or has one name with multiple functionalities. "Poly" means
many and "morph" means forms. Polymorphism provides the ability to a class to have
multiple implementations with the same name. Static Polymorphism:
The same entity (method or operator or object) can perform different operations in
different scenarios. It provides the ability for a class to have multiple implementations with
the same name.

There are two types of polymorphism:

Static Polymorphism (Compile Time/Static Binding)- Method Overloading


Dynamic Polymorphism (Run Time/Dynamic Binding)- Method Overriding

Static Polymorphism (Compile Time/Static Binding)- Method Overloading

Method calls are defined at the time of compilation. Static/Compile time polymorphism can
be implemented using method overloading.

Method overloading allows us to have multiple methods with the same name having
different datatypes of parameter, or a different number of parameters, or both.
Example:

using System;
namespace PolymorphismApplication
{
class Printdata
{
void print(int i)
{
Console.WriteLine("Printing int: {0}", i );
}
void print(double f)
{
Console.WriteLine("Printing float: {0}" , f);
}
void print(string s)
{
Console.WriteLine("Printing string: {0}", s);
}
static void Main(string[] args)
{
Printdata p = new Printdata();
// Call print to print integer
p.print(5);
// Call print to print float
p.print(500.263);
// Call print to print string
p.print("Hello C#");
Console.ReadKey();
}

PROF.DHARESH KUMATAGI, CHETANA BCA COLLEGE, VIJAYAPUR 5


C# AND .NET FRAMEWORK BCA III SEMESTER

}
}

Printing int: 5
Printing float: 500.263
Printing string: Hello C#

Dynamic/Runtime polymorphism

In runtime polymorphism, the method that is called is determined at the runtime


not at compile time. Dynamic/Runtime polymorphism can be implemented using method
overriding.

During inheritance in C#, if the same method is present in both the superclass and
the subclass. Then, the method in the subclass overrides the same method in the
superclass. This is called method overriding.

Dynamic polymorphism is implemented by abstract classes and virtual functions.

C# allows you to create abstract classes that are used to provide partial class
implementation of an interface. Implementation is completed when a derived class inherits
from it. Abstract classes contain abstract methods, which are implemented by the derived
class.
Derived class inherits the methods of parent class with override keyword.

Example:
class Animal // Base class (parent)
{
public virtual void animalSound()
{
Console.WriteLine("The animal makes a sound");
}
}

class Pig : Animal // Derived class (child)


{
public override void animalSound()
{
Console.WriteLine("The pig says: wee wee");
}
}

class Dog : Animal // Derived class (child)


{
public override void animalSound()
{
Console.WriteLine("The dog says: bow wow");
}
}

class Program
{
static void Main(string[] args)
{

PROF.DHARESH KUMATAGI, CHETANA BCA COLLEGE, VIJAYAPUR 6


C# AND .NET FRAMEWORK BCA III SEMESTER

Animal myAnimal = new Animal(); // Create a Animal object


Animal myPig = new Pig(); // Create a Pig object
Animal myDog = new Dog(); // Create a Dog object

myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
}
}

The output will be:

The animal makes a sound


The pig says: wee wee
The dog says: bow wow

Interfaces & inheritance in C#

An interface in c# is reference type. An interface is like abstract class. All methods


of an interface are abstract (a method without implementation). An interface can contain
more than one method, properties, indexers, and events but none of them are
implemented in interface itself. It is the responsibility of the class that implements
interface to define code to implement the members of an interface.

Important points about interfaces

➢ Like abstract classes, interfaces cannot be used to create objects.


➢ Interface methods do not have a body - the body is provided by the "implement" class.
➢ On implementation of an interface, you must override all of its methods.
➢ Interfaces can contain properties and methods, but not fields/variables
➢ Interface members are by default abstract and public
➢ An interface cannot contain a constructor (as it cannot be used to create objects).
➢ Every abstract method of an interface should be implemented by the child class of the
interface without fail (Mandatory).

Why And When To Use Interfaces?

➢ To achieve security - hide certain details and only show the important details of an
object (interface).
➢ C# does not support "multiple inheritance" (a class can only inherit from one base
class). However, it can be achieved with interfaces, because the class can implement
multiple interfaces.
➢ An interface can be used when you want the derived classes to fully implement all of
the methods introduced in the base class.
➢ Abstraction can be achieved via interfaces.
➢ Interface Allows you to decouple a method’s definition from its inheritance hierarchy.
➢ An interface can be used to achieve polymorphic behavior, a single method of an
Interface can have multiple redefinitions into multiple classes of unrelated types. Here,
every derived class is free to provide its own implementation.
➢ Interfaces are best suited to achieve Dispose Pattern by defining an IDisposable
interface.
➢ An Interface doesn’t contain a constructor, which helps to prevent extra roundtrip
when creating an object of the derived class through the reference pointer of the
interface.

PROF.DHARESH KUMATAGI, CHETANA BCA COLLEGE, VIJAYAPUR 7


C# AND .NET FRAMEWORK BCA III SEMESTER

Differences between Class, Abstract Class, and Interface in C#:


➢ Class: Contains only the Non-Abstract Methods (Methods with Method Body).
➢ Abstract Class: Contains both Non-Abstract Methods (Methods with Method Body) and
Abstract Methods (Methods without Method Body).
➢ Interface: Contain only Abstract Methods (Methods without Method Body).

Syntax: <access modifiers> interface <interface name>


{
//Abstract member declaration;
}

Example: class Maths


{
public interface IAddition
{
void Add(); //abstract method
}
}

Implementing an Interface in C#

Interfaces are used as super classes whose properties are inherited by other classes. It is
necessary to create a class that implements interfaces as follows.

Class classname : superclass, inteface1,interface2……..interface n


{
// body of class name
}

Example:
using System;
interface Addition //declaring an interface
{
Int Add();
}
Class Computation : Addition // Extending an interface
{
int x,y;
public Computation(int x, int y) // Constructor
{
this.x=x;
this.y=y;
}
Public int Add() // implementing Add
{
return (x+y);
}
}
Class interfcaeTest
{
public static void Main()
{
Computation c=new Computation(200,100);
Addition a=(Addition) c; //casting
Console.WriteLine(“Sum=” + a.Add());

PROF.DHARESH KUMATAGI, CHETANA BCA COLLEGE, VIJAYAPUR 8


C# AND .NET FRAMEWORK BCA III SEMESTER

}
}

Implementation of multiple interface (multiple interfaces implemented in a


class/multiple inheritance)

using System;
interface Addition
{
int Add ( );
}
interface Multiplication
{
int Mul ( );
}
class Computation : Addition, Multiplication
{
int x, y;
public Computation (int x, int y ) / /Constructor
this.x = x;
this.y = y;
public int Add ( ) / /Implement Add ( )
{
return ( x + y );
}
public int Mul ( )
{ / /Implement Mul ( )
return ( x * y );
}
}
class Interface Test1
{
public static void Main( )
{
Computation com = new Computation (10,20);
Addition add = (Addition ) com; / / casting
Console. WriteLine ("Sum = " + add.Add ( ));
Multiplication mul = (Multiplication) com; / / casting
Console. WriteLine("Product = " + mul.Mul ( ) );
}
}

Multiple implementations of an interface (implementing single interface multiple


times)

using System;
interface Area
{
double Compute ( double x );
}
class Square : Area
{
public double Compute (double x)
{

PROF.DHARESH KUMATAGI, CHETANA BCA COLLEGE, VIJAYAPUR 9


C# AND .NET FRAMEWORK BCA III SEMESTER

return (x * x)
}
}
class Circle : Area
{
public double Compute (double x)
{
return (Math.PI * x * x);
}
}
class Interface Test2
{
public static void Main( )
{
Square sqr = new Square ( );
Circle cir = new Circle ( );
Area area; / /casting
area = sqr as Area; / /casting
Console. WriteLine ("Area of Square ="+ area. Compute(10.0));
area = cir as Area;
Console. WriteLine ("Area of Circle="+ area. Compute(10.0));
}
}

Explicit interface implementation

Explicit interface declarations mean that the interface members are not available
on types other than the interface itself, so implementing types would need to be cast to
the interface before accessing them publicly.

The main reason for explicit interface definitions is to avoid naming conflicts if you
happen to implement two interfaces that contain methods with the same signature... the
explicit definition allows the compiler to keep the signatures distinct enough to resolve.

// C# Program to show the use of Explicit interface implementation


using System;
interface I1
{
void printMethod();
}
interface I2
{
void printMethod();
}

// class C implements two interfaces


class C : I1, I2
{
void I1.printMethod() // Explicitly implements method of I1
{
Console.WriteLine("I1 printMethod");
}
void I2.printMethod() // Explicitly implements method of I2
{
Console.WriteLine("I2 printMethod");

PROF.DHARESH KUMATAGI, CHETANA BCA COLLEGE, VIJAYAPUR 10


C# AND .NET FRAMEWORK BCA III SEMESTER

}
}
class interfaceTest
{
static void Main(string[] args)
{
I1 i1 = new C();
I2 i2 = new C();
i1.printMethod(); // call to method of I1
i2.printMethod(); // call to method of I2

}
}

Calling base class constructor

When we inherit class into another class then object of base class is initialized first. If
a class do not have any constructor, then default constructor will be called. But if we have
created any parameterized constructor then we must initialize base class constructor from
derived class.

We must call constructor from another constructor. When we have to call base class
constructor from derived class then we use base keyword.

When we create the object of ClassA class then first it will call ClassB class constructor
but ClassB class constructor first initialize the base class constructor then ClassB constructor
will be initialized. It is very important point to note down the base class constructor initialized
first.

Example:
public class ClassA
{
public int p, q;
public ClassA(int p1, int p2)
{
p = p1;
q = p2;
}
public int sum()
{
return (p + q);
}

}
//derived class/ child class
public class ClassB : ClassA
{
public int r;

PROF.DHARESH KUMATAGI, CHETANA BCA COLLEGE, VIJAYAPUR 11


C# AND .NET FRAMEWORK BCA III SEMESTER

public ClassB(int r1, int p1, int p2) : base(p1, p2)


{
r = r1;
}
public int Add()
{
return (r+p+q);
}
}
class Test
{
public static void Main()
{
ClassB b = new ClassB(2, 3, 4);
Console.WriteLine("Sum of 2 numbers:{0}", b.sum());
Console.WriteLine("Sum of 3 numbers:{0}", b.Add());
Console.ReadLine();
}
}
}

#output
Sum of 2 numbers:7
Sum of 3 numbers:9

Method overriding

In c#, Method Overriding means override a base class method in the derived class
by creating a method with the same name and signatures to perform a different task. The
Method Overriding in c# can be achieved using override & virtual keywords and the
inheritance principle.

If we want to change the behavior of the base class method in a derived class, then
we need to use method overriding. The base class method we want to override in the
derived class needs to be defined with a virtual keyword. We need to use the override
keyword in the derived class while defining the method with the same name and
parameters then only we can override the base class method in a derived class.

In c#, the Method Overriding is also called run time polymorphism or late binding.

Method overriding with virtual and override keyword


Example:
class Animal // Base class (parent)
{
public virtual void animalSound()
{
Console.WriteLine("The animal makes a sound");
}
}

class Pig : Animal // Derived class (child)


{

PROF.DHARESH KUMATAGI, CHETANA BCA COLLEGE, VIJAYAPUR 12


C# AND .NET FRAMEWORK BCA III SEMESTER

public override void animalSound()


{
Console.WriteLine("The pig says: wee wee");
}
}

class Dog : Animal // Derived class (child)


{
public override void animalSound()
{
Console.WriteLine("The dog says: bow wow");
}
}

class Program
{
static void Main(string[] args)
{
Animal myAnimal = new Animal(); // Create a Animal object
Animal myPig = new Pig(); // Create a Pig object
Animal myDog = new Dog(); // Create a Dog object

myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
}
}

The output will be:

The animal makes a sound


The pig says: wee wee
The dog says: bow wow

Using base keyword to implement polymorphism

using System;
namespace PolymorphismDemo
{
class Class1
{
//Virtual Function (Overridable Method)
public virtual void Show()
{
//Parent Class Logic Same for All Child Classes
Console.WriteLine("Parent Class Show Method");
}
}

class Class2 : Class1


{
//Overriding Method
public override void Show()
{
base.Show(); //Calling Parent Class Show method

PROF.DHARESH KUMATAGI, CHETANA BCA COLLEGE, VIJAYAPUR 13


C# AND .NET FRAMEWORK BCA III SEMESTER

Console.WriteLine("Child Class Show Method");


}
}

class Program
{
static void Main(string[] args)
{
Class1 obj1 = new Class2();
obj1.Show();

Class2 obj2 = new Class2();


obj2.Show();
Console.ReadKey();
}
}
}

#output
Parent Class Show Method
Child Class Show Method
Parent Class Show Method
Child Class Show Method

Non-inheritable classes (sealed classes)

A sealed class, in C#, is a class that cannot be inherited by any class but can be
instantiated.

The design intent of a sealed class is to indicate that the class is specialized and there is
no need to extend it to provide any additional functionality through inheritance to override
its behaviour.

C# Sealed Keyword Features

The following are the important points which we need to remember about the sealed
keyword in the c# programming language.

➢ In c#, to apply a sealed keyword on a method or property, it must always use with
override.
➢ In c#, we should not use an abstract modifier with a sealed class because an
abstract class must be inherited by a class that provides an implementation of the
abstract methods or properties.
➢ In c#, the local variables cannot be sealed.
➢ In c#, structs are implicitly sealed; they cannot be inherited.

Example:

using System;
namespace SealedClass {
sealed class Animal {
}

// trying to inherit sealed class Error Code

PROF.DHARESH KUMATAGI, CHETANA BCA COLLEGE, VIJAYAPUR 14


C# AND .NET FRAMEWORK BCA III SEMESTER

class Dog : Animal {


}
class Program {
static void Main (string [] args) {
// create an object of Dog class
Dog d1 = new Dog();
Console.ReadLine();
}
}
}

#output
error CS0509: 'Dog': cannot derive from sealed type 'Animal'

Boxing and unboxing in C#

Boxing and unboxing in C# allow developers to convert .NET data types from value type
to reference type and vice versa.

Boxing: Converting a value type to a reference type is called called boxing in C#. A boxing
conversion permits any value-type to be implicitly converted to the type object or to any
interface-type implemented by the value-type.

Unboxing: Converting a reference type to a value type is called unboxing in C#. An


unboxing conversion permits an explicit conversion from type object to any value-type or
from any interface-type to any value-type that implements the interface-type.
Boxing

Reference types store on heap where it contains the address of the value and value
type is just an actual value stored on the stack.
Now, as shown in the first example, int i is assigned to object o. Object o must be
an address and not a value itself. So, the CLR boxes the value type by creating a new
System.Object on the heap and wraps the value of i in it and then assigns an address of
that object to o. So, because the CLR creates a box on the heap that stores the value, the
whole process is called 'Boxing'.

The following figure illustrates the boxing process.

int i = 10;
object o = i; //performs boxing

Example:

PROF.DHARESH KUMATAGI, CHETANA BCA COLLEGE, VIJAYAPUR 15


C# AND .NET FRAMEWORK BCA III SEMESTER

using System;
class Program
{
static void Main(string[] args)
{
int num1 = 42;
object obj1 = num1;
System.ConsoleWriteLine("Value is : {0}", num1);
// Value is : 42
System.ConsoleWriteLine("Object is : {0}", obj1);
// Object is : 42
}
}
#output
Value is:42
Object is:42

In the example above, the num1 variable is the value, and we boxed it into a reference
called obj1. The obj1 reference is of type object, which is the base reference type in .NET.

Unboxing
Unboxing is the reverse of boxing. It is the process of converting a reference type to value
type. Unboxing extract the value from the reference type and assign it to a value type.

object o = 10;
int i = (int)o; //performs unboxing

using System;
class Program
{
static void Main(string[] args)
{
int num1 = 42;
object obj1 = num1;
num1 = 10_000;
int num2 = (int)obj1;
System.ConsoleWriteLine("Value is : {0}", num1);
// Value is : 10000
System.ConsoleWriteLine("Object is : {0}", obj1);
// Object is : 42
System.ConsoleWriteLine("Value2 is : {0}", num2);
// Value is : 42
}

PROF.DHARESH KUMATAGI, CHETANA BCA COLLEGE, VIJAYAPUR 16


C# AND .NET FRAMEWORK BCA III SEMESTER

#output
Value is : 10000
Object is : 42
Value2 is : 42

Delegates

The general meaning of the delegate is “a person is acting for another person”. In C# a method
can act for another method.

Delegate in c# is a class type object and it is used to invoke a method that has been
encapsulated into it at the time its creation.

A delegate declaration defines a class using System. Delegate base class. Delegates are any
function whose signature matches the delegate signature exactly.

The delegate instance holds the reference to delegate methods. Instance is used to invoke
the methods. Indirectly.

Why do we need delegates in C#?

➢ Delegates are similar to C++ function pointers, but are type safe.
➢ Delegate gives a name to a method signature.
➢ Delegates allow methods to be passed as parameters.
➢ Delegates can be used to define callback methods.
➢ Delegates can be chained together; for example, multiple methods can be called on
a single event.
➢ Delegate helps in code optimization.

Delegate Declaration
Syntax:

<access modifier> delegate <return-type> <delegate-name> (<parameter-list>)

PROF.DHARESH KUMATAGI, CHETANA BCA COLLEGE, VIJAYAPUR 17


C# AND .NET FRAMEWORK BCA III SEMESTER

//class body;

Access modifiers can be public, private, protected and internal. Delegate is keyword used declare a
delegate type. Return-type indicates return type of delegate. Parameter-list identifies the signature
of a delegate. Delegate-name is any valid identifier given by the user.

Delegates are implicitly sealed so they cannot be derived.

Example:

using System;
//declaration of delegate
public delegate int Maths (int x, int y)
class Cal
{
//delegate method definition
public static int Add(int a, int b)
{
return (a+b);
}
public static int Mul(int a, int b)
{
return (a*b);
}
}
class delegateTest
{
Public static void Main()
{
//delegate instances
Maths m1=new Maths(Cal.Add);
Maths m2=new Maths(Cal.Mul);
//invoking delegates
int m=m1(20,10);
int n=m2(20,10);
Console.WriteLine(“m=”+m);
Console.WriteLine(“n=”+n);
}
}

Types of delegates
1. Single cast delegate
2. Multi cast delegate

Single cast delegate

A single cast delegate holds the reference of only single method. It is derived from
System.Delegate class.

PROF.DHARESH KUMATAGI, CHETANA BCA COLLEGE, VIJAYAPUR 18


C# AND .NET FRAMEWORK BCA III SEMESTER

Example:
using System;
//declaration of delegate
public delegate int Maths (int x, int y)
class Cal
{
//delegate method definition
public static int Add(int a, int b)
{
return (a+b);
}
public static int Mul(int a, int b)
{
return (a*b);
}
}
class delegateTest
{
Public static void Main()
{
//delegate instances
Maths m1=new Maths(Cal.Add);
Maths m2=new Maths(Cal.Mul);
//invoking delegates
int m=m1(20,10);
int n=m2(20,10);
Console.WriteLine(“m=”+m);
Console.WriteLine(“n=”+n);
}
}

Multi cast delegate

A delegate which holds the reference of more than one method is called multi-cast delegate.
A multicast delegate only contains the reference of methods which return type is void. The +
and += operators are used to combine delegate instances. Multicast delegates are considered
equal if they reference the same methods in the same order.
It is derived from System.MulticastDelegate class.

Example:
using System;
delegate void City();
class MDelegate
{

PROF.DHARESH KUMATAGI, CHETANA BCA COLLEGE, VIJAYAPUR 19


C# AND .NET FRAMEWORK BCA III SEMESTER

static public void display()


{
Console.WriteLine(“New Delhi”);
}
static public void print()
{
Console.WriteLine(“New York”);
}
}
class DelegateTest
{
public static void Main()
{
City c1=new City (MDelegate.display);
City c2=new City (MDelegate.print);
City c3=c1+c2;
City c4=c2+c1;
City c5=c3-c2;
//invoking the delegates
c3();
c4();
c5();
}
}

#Output
New Delhi
New York
New York
New Delhi
New Delhi

Events

Events are user actions such as key press, clicks, mouse movements, etc., or some occurrence
such as system generated notifications. Applications need to respond to events when they
occur.

The event is an encapsulated delegate. C# and .NET both support the events with the
delegates. When the state of the application changes, events and delegates give the
notification to the client application. Delegates and Events both are tightly coupled for
dispatching the events, and event handling require the implementation of the delegates.

➢ Event Handlers in C# return void and take two parameters.


➢ The First parameter of Event - Source of Event means publishing object.

PROF.DHARESH KUMATAGI, CHETANA BCA COLLEGE, VIJAYAPUR 20


C# AND .NET FRAMEWORK BCA III SEMESTER

➢ The Second parameter of Event - Object derived from EventArgs.


➢ The publishers determines when an event is raised and the subscriber determines
what action is taken in response.
➢ An Event can have so many subscribers.
➢ Events are basically used for the single user action like button click.
➢ If an Event has multiple subscribers then event handlers are invoked synchronously.

A publisher is an object that contains the definition of the event and the delegate.
A subscriber is an object that accepts the event and provides an event handler.

using System;
namespace Example
{
public delegate string demoDelegate(string str);
class MyEvents
{
event demoDelegate myEvent;
public MyEvents()
{
this.myEvent += new demoDelegate(this.Display);
}
public string Display(string name)
{
return (name);
}
static void Main(string[] args) {
MyEvents e = new MyEvents();
string res = e.myEvent("Jack");
Console.WriteLine("RESULT...\n"+res);
}
}
}

#output
RESULT...
Student: Jack
Subject: Science

Operator Overloading

PROF.DHARESH KUMATAGI, CHETANA BCA COLLEGE, VIJAYAPUR 21


C# AND .NET FRAMEWORK BCA III SEMESTER

What is Operator Overloading in C#?

Operator overloading is the ability to make an operator perform different operations on


operands of different data types.
In C#, it is possible to make operators work with user-defined data types like classes. That
means C# has the ability to provide the operators with a special meaning for a data type, this
ability is known as operator overloading. For example, we can overload the + operator in a
class like String so that we can concatenate two strings by just using +.

The syntax for C# Operator Overloading:


To overload an operator in C#, we use a special operator function. We define the function
inside the class or structure whose objects/variables we want the overloaded operator to
work with. The Syntax for Operator Overloading in C# is shown below.

Here,
1. The return type is the return type of the function.
2. the operator is a keyword.
3. Op is the symbol of the operator that we want to overload. Like: +, <, -, ++, etc.
4. The type must be a class or struct. It can also have more parameters.
5. It should be a static function.

There are multiple operators in C#.

We can overload all the binary operators i.e +, -, *, /, %, &, |, <<, >>.
We can overload all the unary operators i.e. ++, –, true, false, + , -, ~.
Some operators like &&, ||,[] ,() cannot be overloaded.
We can overload relational operators in pairs. These are ==, =, <, >, <= , >= etc.
We can overload compound operators as they are already overloaded with respect to the
binary operator.

Example: Adding two complex numbers using Operator overloading


using System;
public class Complex
{
public int real;
public int imaginary;
public Complex(int real, int imag)
{
this.real = real;
this.imag = imag;
}
// Syntax of Operator Overloading
public static Complex operator +(Complex n1, Complex n2)

PROF.DHARESH KUMATAGI, CHETANA BCA COLLEGE, VIJAYAPUR 22


C# AND .NET FRAMEWORK BCA III SEMESTER

{
return new Complex(n1.real + n2.real, n1.imag + n2.imag);
}
// Override the ToString method to display an complex number in the suitable format:
public override string ToString()
{
return (String.Format("{0} + {1}i", real, imag));
}
public static void Main()
{
Complex cnum1 = new Complex(4, 5);
Complex cnum2 = new Complex(5, 6);
// Add two Complex objects (num1 and num2) through the
Complex addition = cnum1 + cnum2;
// Print the numbers
Console.WriteLine("First complex number: {0}", cnum1);
Console.WriteLine("Second complex number: {0}", cnum2);
Console.WriteLine(“The sum of the two numbers: {0}", addition);
// Hault the output screen
Console.Read();
}
}

#Output
First Complex Number : 4+5i
Second Complex Number : 5+6i
The sum of the two numbers: 9 + 11i

Contrasting (differentiate) Abstract class and interfaces

SN Abstract Class Interface


01. In C#, An Abstract class can However, every method, property, and
have public, private, or protected class event contained within an Interface is
members. always public by default.
02. An abstract class in C# can contain An interface in C# can’t contain
constructors. a constructor
03. Abstract classes do not support On the other side, the Interface supports
multiple Inheritance multiple Inheritance in C#.
04. A class can be inherited by only one A class can inherit by multiple interfaces.
abstract class.
05. An abstract class in C# can be fully An interface contains only the signatures of
implemented, partially implemented, methods, properties, events, or indexers
or not implemented at all. not the implementation.
06. Abstract class members such as Interface members can’t be defined as
methods or properties can be defined abstract, virtual, static, or sealed.
as abstract, virtual, static, or sealed.
07. Abstract class can contains both An interface is used when you only need the
declaration and Implementation of signature of a method and not the
methods. implementation.

PROF.DHARESH KUMATAGI, CHETANA BCA COLLEGE, VIJAYAPUR 23


C# AND .NET FRAMEWORK BCA III SEMESTER

08. An abstract class can contain fields and An interface cannot have fields.
constants.
09. If multiple implementations of methods If multiple unrelated classes only share
are of the same kind and use common method signatures and have different
behavior, then it’s better to use an implementations of methods, then it is
abstract class. So that the common better to use Interface.
implementation code does not need to
be repeated in each of the descending
or subclasses.
10. An abstract class can contain the main An interface can’t contain the main method.
method in C#.

C# Abstract Class

An abstract class is an incomplete class or special class we can't be instantiated. The


purpose of an abstract class is to provide a blueprint for derived classes and set some
rules what the derived classes must implement when they inherit an abstract class.

We can use an abstract class as a base class and all derived classes must implement
abstract definitions. An abstract method must be implemented in all non-abstract classes
using the override keyword. After overriding the abstract method is in the non-Abstract
class. We can derive this class in another class and again we can override the same
abstract method with it.

C# Abstract Class Features

➢ As we cannot create objects of an abstract class, we must create a derived class


from it.
➢ An abstract class can inherit from a class and one or more interfaces.
➢ An abstract class can implement code with non-Abstract methods.
➢ An Abstract class can have modifiers for methods, properties etc.
➢ An Abstract class can have constants and fields.
➢ An abstract class can implement a property.
➢ An abstract class can have constructors or destructors.
➢ An abstract class cannot be inherited from by structures.
➢ An abstract class cannot support multiple inheritance.

Example:
using System;
namespace AbstractClass
{
abstract class Animal
{
public abstract void makeSound(); // abstract method
}
class Dog : Animal // inheriting from abstract class
{
// provide implementation of abstract method
public override void makeSound()
{
Console.WriteLine("Bark Bark");

PROF.DHARESH KUMATAGI, CHETANA BCA COLLEGE, VIJAYAPUR 24


C# AND .NET FRAMEWORK BCA III SEMESTER

}
}
class Program
{
static void Main (string [] args) {
Dog obj = new Dog(); // create an object of Dog class
obj.makeSound();
Console.ReadLine();
}
}
}

#output

Bark Bark

PROF.DHARESH KUMATAGI, CHETANA BCA COLLEGE, VIJAYAPUR 25

You might also like