UNIT 3 Notes - 2023-24 3rd Sem
UNIT 3 Notes - 2023-24 3rd Sem
C# is a true object oriented programming language. Hence, classes form the bases for all the C#
programs. Anything that we want to represent in C# is encapsulated inside a class. The class is a
template of user defined type that contains instance variables, static members and methods that
operate upon them. An object is an instance of a class or can also be defined as a variable of type
class.
Encapsulation
It provides an ability to hide the internal details of an object from its users. The outside user may
not be able to change the state of an object directly. However the state of an object can be altered
using its methods. The class construct ensures encapsulation and the keywords private, public,
protected etc ensures data hiding.
Inheritance
This concept is used to build new classes from existing classes. The existing class is known as
base(super/parent) class and the new class is known as derived (sub/child) class. The concept of
inheritance facilitates reusability of existing code and improves the productivity of the
programmer.
Polymorphism
It is an important concept in object oriented programming. It refers to the ability to take more
than one forms.
Example : An operator or a method may exhibit different behaviour in different situations. The
a. Method overloading
b. operator overloading
2. Runtime polymorphism
a. Method overriding
In C# private variables can only be accessed within the same class (an outside class has no
access to it). However, sometimes we need to access them and it can be done with properties.
A property is like a combination of a variable and a method, and it has two methods: a get and
a set method:
KLS Gogte BCA – Belagavi SEM-III C# and .NET Framework –UNIT 3
The general form of a property is shown below:
type name {
get{
//get method code
}
set{
//set method code
}
}
Example:
class Person
{
private string name; // field
public string Name // property
{
get { return name; } // get method
set { name = value; } // set method
}
}
Example explained
The Name property is associated with the name field. It is a good practice to use the same
name for both the property and the private field, but with an uppercase first letter.
The get method returns the value of the variable name.
The set method assigns a value to the name variable. The value keyword represents the
value we assign to the property.
Example Program
using System;
namespace Get_Set_Demo
{
class Student
{
private string name; // field
private int rollno; // field
class Program
{
static void Main(string[] args)
{
Student s = new Student();
s.Name = "Aditya";
s.RollNo = 104;
Console.WriteLine("Student Name = "+s.Name);
Console.WriteLine("Student Roll Number = "+s.RollNo);
}
}
}
Inheritance
For example, consider two classes A and B. We can create a class hierarchy such that B is
derived from A.
Syntax
class derived_class_name : base_class_name
{
…………
}
In the above syntax, the : signifies that the properties of base class are extended to the derived
class. Classical inheritance may be implemented in several ways
Multiple Inheritance
In this type, a class is derived from multiple base classes. In C# multiple inheritance is
implemented using interface.
Multilevel inheritance
A common requirement in Object Oriented Programming is the use of derived class concepts and
use it extensively in building a class library or chain of classes. The derived class further can be
used as base class to derive another class, such an inheritance is called as multilevel inheritance.
class A
{
A super class ========
========
}
B Intermediate class B : A
class {
==========
==========
C sub class }
class C : B
{
=========
=========
}
KLS Gogte BCA – Belagavi SEM-III C# and .NET Framework –UNIT 3
Hierarchical inheritance
It is a way of transmitting features from a parent class to a base, child, or subclass in terms of
technical terms and the object-oriented aspect. The parent class or superclass is the class from
which the properties are taken, i.e. the features are inherited. Hierarchical inheritance describes
a situation in which a parent class is inherited by multiple subclasses. A type of inheritance in
which more than one class is inherited from a single parent or base class is known as
hierarchical inheritance.
B C D
//C# program to demonstrate Single Inheritance
using System;
namespace Demo_Inheritance
{
class Base
{
public void basePublic()
{
Console.WriteLine("Base Public");
}
protected void baseProtected()
{
Console.WriteLine("Base Protected");
}
private void basePrivate()
{
Console.WriteLine("Base Private");
}
}
class Inheritance_1
b.basePublic();
d.printDerived();
d.basePublic();
// d.baseProtected(); // Error
//d.basePrivate();
using System;
namespace Demo_Inheritance
private int x;
protected int y;
public int z;
Console.WriteLine("Eating");
Console.WriteLine("Sleeping");
Console.WriteLine("Drinking");
Console.WriteLine("Barking");
drink();
eat();
// x = 10; Error
z = 30;
class Inheritance_2
d1.eat();
d1.bark();
d1.z = 40;
//d1.sleep(); // Error
// a.sleep(); // Error
// d1.drink(); // Error
Method Overriding
Inheritance enables to define methods repeatedly in super class and sub class. However,
sometimes it may be necessary to override a method used in superclass. In C#, method
overriding is implemented as follow:
Specify the method in the base class as virtual
Implement the method in the sub class using the keyword override
namespace Demo_Inheritance
{
class OverrideDemo
{
public static void Main()
{
Pigeon p = new Pigeon();
p.moves(); // calls the moves() method of derived class
}
}
}
Method Hiding
Sometimes it may be necessary to derive from the classes provided by someone else. We may
also wish to re-define some of the methods present in such classes. For this, C# provides the
modifier new that hides a base class method and the new derived class method must be used
instead of the super class method.
Abstract Classes
Sometime it is necessary to have one base class and a number of derived classes. The top
most class simply act as base for other classes and is not useful on its own. In such
situations we may never create the object of the base class. Such classes can be made as an
abstract classes.
Abstract classes are implemented by using abstract modifier at the time of class definition.
Abstract methods are implemented by using abstract modifier at the time of declaring a
method.
Once the class is defined as abstract then the object of that class cannot be created. Hence, it
cannot be instantiated.
Ex:
abstract class Base
{
……
……
}
Class Derived : Base
{
……
……
}
Base b; // Error
Derived d; // No error
using System;
class AbstarctClass
{
public static void Main()
{
bike b = new bike();
b.Moves(); // Overridden method will be called (derived class)
b.runs(); // Inheritted method will be called (base class)
// Attempting to create an object of abstract class results in error
// Automobile a = new Automobile(); //Error
}
}
Eg:
abstract class Base
{
……
……
}
class ParameterClass
{
public static void ListenToMe(IAnimal Listener)
{
KLS Gogte BCA – Belagavi SEM-III C# and .NET Framework –UNIT 3
Listener.sound();
}
}
class InterfaceAsParameterDemo
{
public static void Main()
{
//Create an object of the interface but do not instantiate
IAnimal myAnimal;
Unboxing
Conversion of an object type on heap to a value type on stack is known as unboxing.
Ex:
int i = 100;
object obj = i;
int j = (int)obj;
KLS Gogte BCA – Belagavi SEM-III C# and .NET Framework –UNIT 3
During unboxing operation, C# checks whether the value is already boxed and whether it is large
enough to hold the value of object, otherwise the operation may result in runtime error.
Delegates in C#
Definition:
Delegates in C# are like pointers to functions. They hold the reference of a function and this
reference can be hanged at run time. Delegates are implicitly derived from System.Delegate
class.
A delegate can be declared using the delegate keyword before the function signature.
The syntax of a delegate is given as follows:
Types of Delegates:
1. Single Cast Delegate(Same as previous contents)
2. Multicast Delegate
Multicast Delegate
The delegate can point to multiple methods. A delegate that points multiple methods is
called a multicast delegate.
It is used to hold the reference of multiple methods with a single delegate.
By using "+" operator, we can add the multiple method references to the delegate object.
Same way, by using "-" operator we can remove the method references from the delegate
object.
By using delegate we can pass methods as the parameter.
C# Events
An event is a delegate type class member that is used by the object or class to provide
notification to other objects that an event has occurred. The client object can act on an event by
adding an event handler to the event.
In this model, you have publishers who will do some logic and publish an "event." Publishers
will then send out their event only to subscribers who have subscribed to receive the specific
event.
In C#, any object can publish a set of events to which other applications can subscribe. The class
who raises events is called Publisher, and the class who receives the notification is
called Subscriber. There can be multiple subscribers of a single event
When the publishing class raises an event, all the subscribed applications are notified. The
following figure shows this mechanism.
1. Declare a delegate.
2. Declare a variable of the delegate with event keyword.
In the above examples, EventHandler and RateChange are delegates and Click and Rate are
events.
Since events are based on delegates, we must first declare a delegate and then declare an instance
of the delegate using the keyword event.
ec.TriggerEvent();
Console.ReadKey();
}
KLS Gogte BCA – Belagavi SEM-III C# and .NET Framework –UNIT 3
public void EventCatch(string str)
{
Console.WriteLine(str);
}
}
Operator Overloading
C# operators can be defined to work with the user-defined data types such as structs and classes
in much the same way as the built-in types. For instance, C# permits us to add two class objects
with the same syntax that is applied to the basic types.
Example:
Vector u1,u2,u3;
-------
where Vector is a class or a struct. Two vectors u1 and u2 are added (like a simple type) to give
a third vector u3. This means , C# has the ability to provide the operators with a special meaning
for a data type. This mechanism of giving such special meaning to an operator is known as
operator overloading.
The retval (return value) type is the type that we get when we use this operator.
The arglist is the list of arguments passed. The number of arguments will be one for the unary
operators and two for the binary operators.