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

unit-3c#.(modified)docx

The document covers key concepts in C# programming including encapsulation, inheritance, polymorphism, abstraction, and interfaces. It provides examples of single-level and multi-level inheritance, static and dynamic polymorphism, and the differences between abstract classes and interfaces. Additionally, it discusses operator overloading and includes code snippets to illustrate these concepts.

Uploaded by

Ganesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

unit-3c#.(modified)docx

The document covers key concepts in C# programming including encapsulation, inheritance, polymorphism, abstraction, and interfaces. It provides examples of single-level and multi-level inheritance, static and dynamic polymorphism, and the differences between abstract classes and interfaces. Additionally, it discusses operator overloading and includes code snippets to illustrate these concepts.

Uploaded by

Ganesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

C# Notes

C# Encapsulation:
Encapsulation is the concept of wrapping data into a single unit. It collects data
members and member functions into a single unit called class. The purpose of
encapsulation is to prevent alteration of data from outside. This data can only be
accessed by getter functions of the class.

A fully encapsulated class has getter and setter functions that are used to read and
write data. This class does not allow data access directly.

Here, we are creating an example in which we have a class that encapsulates


properties and provides getter and setter functions.

Example
namespace AccessSpecifiers
{
class Student
{
// Creating setter and getter for each property
public string ID { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
}
using System;
namespace AccessSpecifiers
{
class Program
{
static void Main(string[] args)
{
Student student = new Student();
// Setting values to the properties
Student.ID = "101";
Student.Name = "Mohan Ram";
Student.Email = "[email protected]";
// getting values
Console.WriteLine("ID = "+student.ID);
Console.WriteLine("Name = "+student.Name);
Console.WriteLine("Email = "+student.Email);
}
}
}

Dr.G.S.Puranik 1
C# Notes

C# Inheritance:
In C#, inheritance is a process in which one object acquires all the properties and
behaviors of its parent object automatically. In such way, you can reuse, extend or
modify the attributes and behaviors which is defined in other class.

In C#, the class which inherits the members of another class is called derived class
and the class whose members are inherited is called base class. The derived class is
the specialized class for the base class.

Advantage of C# Inheritance
Code reusability: Now you can reuse the members of your parent class. So, there is no
need to define the member again. So less code is required in the class.

C# Single Level Inheritance Example: Inheriting Fields


When one class inherits another class, it is known as single level inheritance. Let's see
the example of single level inheritance which inherits the fields only.

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);

}
}

Output:

Salary: 40000
Bonus: 10000
In the above example, Employee is the base class and Programmer is the derived class.

Dr.G.S.Puranik 2
C# Notes

C# Single Level Inheritance Example: Inheriting Methods


Let's see another example of inheritance in C# which inherits methods only.

using System;
public class Animal
{
public void eat()
{ Console.WriteLine("Eating..."); }
}
public class Dog: Animal
{
public void bark()
{ Console.WriteLine("Barking..."); }
}
class TestInheritance2{
public static void Main(string[] args)
{
Dog d1 = new Dog();
d1.eat();
d1.bark();
}
}
Output:

Eating...
Barking...

Dr.G.S.Puranik 3
C# Notes

C# Multi Level Inheritance Example:


When one class inherits another class which is further inherited by another class, it is
known as multi level inheritance in C#. Inheritance is transitive so the last derived
class acquires all the members of all its base classes.

Let's see the example of multi level inheritance in C#.

using System;
public class Animal
{
public void eat()
{ Console.WriteLine("Eating..."); }
}
public class Dog: Animal
{
public void bark()
{ Console.WriteLine("Barking..."); }
}
public class BabyDog : Dog
{
public void weep()
{ Console.WriteLine("Weeping..."); }
}
class TestInheritance2{
public static void Main(string[] args)
{
BabyDog d1 = new BabyDog();
d1.eat();
d1.bark();
d1.weep();
}
}

Output:
Eating...
Barking...
Weeping…

Dr.G.S.Puranik 4
C# Notes

Polymorphism in c#:
The word polymorphism means having many forms. In object-oriented programming
paradigm, polymorphism is often expressed as 'one interface, multiple functions'.
Polymorphism can be static or dynamic. In static polymorphism, the response to a
function is determined at the compile time. In dynamic polymorphism, it is decided
at run-time.
Static Polymorphism:
The mechanism of linking a function with an object during compile time is called
early binding. It is also called static binding. C# provides two techniques to
implement static polymorphism. They are −
 Function overloading
 Operator overloading
We discuss operator overloading in next chapter.

Function Overloading:

You can have multiple definitions for the same function name in the same scope. The
definition of the function must differ from each other by the types and/or the number
of arguments in the argument list. You cannot overload function declarations that
differ only by return type.
The following example shows using function print() to print different data types −
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();
}

Dr.G.S.Puranik 5
C# Notes

}}
When the above code is compiled and executed, it produces the following result −
Printing int: 5
Printing float: 500.263
Printing string: Hello C++

Dynamic Polymorphism

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. The derived classes have more specialized functionality.
Here are the rules about abstract classes −

You cannot create an instance of an abstract class


You cannot declare an abstract method outside an abstract class


When a class is declared sealed, it cannot be inherited, abstract classes cannot
be declared sealed.

The following program demonstrates an abstract class −
using System;
namespace PolymorphismApplication {
abstract class Shape {
public abstract int area();
}

class Rectangle: Shape {


private int length;
private int width;

public Rectangle( int a = 0, int b = 0) {


length = a;
width = b;
}
public override int area () {
Console.WriteLine("Rectangle class area :");
return (width * length);
}
}
class RectangleTester {
static void Main(string[] args) {
Rectangle r = new Rectangle(10, 7);
double a = r.area();

Dr.G.S.Puranik 6
C# Notes

Console.WriteLine("Area: {0}",a);
Console.ReadKey();
}
}}
When the above code is compiled and executed, it produces the following result −
Rectangle class area :
Area: 70
When you have a function defined in a class that you want to be implemented in an
inherited class(es), you use virtual functions. The virtual functions could be
implemented differently in different inherited class and the call to these functions will
be decided at runtime.
Dynamic polymorphism is implemented by abstract classes and virtual functions.
The following program demonstrates this −
using System;
namespace PolymorphismApplication {
class Shape {
protected int width, height;

public Shape( int a = 0, int b = 0) {


width = a;
height = b;
}
public virtual int area() {
Console.WriteLine("Parent class area :");
return 0;
}
}
class Rectangle: Shape {
public Rectangle( int a = 0, int b = 0): base(a, b) {

}
public override int area () {
Console.WriteLine("Rectangle class area :");
return (width * height);
}
}
class Triangle: Shape {
public Triangle(int a = 0, int b = 0): base(a, b) {
}
public override int area() {
Console.WriteLine("Triangle class area :");
return (width * height / 2);
}
}
class Caller {
public void CallArea(Shape sh) {
int a;

Dr.G.S.Puranik 7
C# Notes

a = sh.area();
Console.WriteLine("Area: {0}", a);
}
}
class Tester {
static void Main(string[] args) {
Caller c = new Caller();
Rectangle r = new Rectangle(10, 7);
Triangle t = new Triangle(10, 5);

c.CallArea(r);
c.CallArea(t);
Console.ReadKey();
}
}}
When the above code is compiled and executed, it produces the following result −
Rectangle class area:
Area: 70
Triangle class area:
Area: 25

Abstraction Class:

Data abstraction is the process of hiding certain details and showing only essential
information to the user.
Abstraction can be achieved with either abstract classes or interfaces
The abstract keyword is used for classes and methods:

Abstract class: is a restricted class that cannot be used to create objects (to access it, it
must be inherited from another class).

Abstract method: can only be used in an abstract class, and it does not have a body.
The body is provided by the derived class (inherited from).
An abstract class can have both abstract and regular methods:

abstract class Animal


{
public abstract void animalSound();
public void sleep()
{
Console.WriteLine("Zzz");
}
}

Dr.G.S.Puranik 8
C# Notes

Example:

Using System;

namespace MyApplication
{
// Abstract class
abstract class Animal
{
// Abstract method (does not have a body)
public abstract void animalSound();
// Regular method
public void sleep()
{
Console.WriteLine("Zzz");
}
}

// Derived class (inherit from Animal)


class Pig : Animal
{
public override void animalSound()
{
// The body of animalSound() is provided here
Console.WriteLine("The pig says: wee wee");
}
}

class Program
{
static void Main(string[] args)
{
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}
}

O/P:

The pig says: wee wee


Zzz

Dr.G.S.Puranik 9
C# Notes

Example:
using System;

public abstract class Animal


{
public abstract string Sound { get; }

public virtual void Move()


{
Console.WriteLine("Moving...");
}
}

public class Cat : Animal


{
public override string Sound => "Meow";

public override void Move()


{
Console.WriteLine("Walking like a cat...");
}
}

public class Dog : Animal


{
public override string Sound => "Woof";

public override void Move()


{
Console.WriteLine("Running like a dog...");
}
}

class Program
{
static void Main(string[] args)
{
Animal[] animals = new Animal[] { new Cat(), new Dog() };

foreach (Animal animal in animals)


{
Console.WriteLine($"The {animal.GetType().Name} goes {animal.Sound}");
animal.Move();
}
}
}

Dr.G.S.Puranik 10
C# Notes

Output:
The Cat goes Meow
Walking like a cat...
The Dog goes Woof
Running like a dog...
Abstraction in C# is the process to hide the internal details and show only the
functionality. The abstract modifier indicates the incomplete implementation. The
keyword abstract is used before the class or method to declare the class or method as
abstract. Also, the abstract modifier can be used with indexers, events, and properties.

C# Interfaces:
C# allows the user to inherit one interface into another interface. When a class
implements the inherited interface then it must provide the implementation of all the
members that are defined within the interface inheritance chain.
Important Points:

If a class implements an interface, then it is necessary to implement all the method


that defined by that interface including the base interface methods. Otherwise, the
compiler throws an error.
If both derived interface and base interface declares the same member then the base
interface member name is hidden by the derived interface member name.
Syntax:

// declaring an interface
access_modifier interface interface_name
{
// Your code
}

// inheriting the interface


access_modifier interface interface_name : interface_name
{
// Your code
}

Dr.G.S.Puranik 11
C# Notes

Example:
using System;

// declaring an interface
public interface A {

// method of interface
void mymethod1();
void mymethod2();
}

// The methods of interface A


// is inherited into interface B
public interface B : A {

// method of interface B
void mymethod3();
}

// Below class is inheriting


// only interface B
// This class must
// implement both interfaces
class Geeks : B
{

// implementing the method


// of interface A
public void mymethod1()
{
Console.WriteLine("Implement method 1");
}

// Implement the method


// of interface A
public void mymethod2()
{
Console.WriteLine("Implement method 2");
}

// Implement the method


// of interface B
public void mymethod3()
{
Console.WriteLine("Implement method 3");
}
}

// Driver Class

Dr.G.S.Puranik 12
C# Notes

class GFG {

// Main method
static void Main(String []args)
{

// creating the object


// class of Geeks
Geeks obj = new Geeks();

// calling the method


// using object 'obj'
obj.mymethod1();
obj.mymethod2();
obj.mymethod3();
}
}

O/P:

Implement method 1
Implement method 2
Implement method 3

Example :

using System;

namespace InheritanceApplication {
class Shape {
public void setWidth(int w) {
width = w;
}

public void setHeight(int h) {


height = h;
}

protected int width;


protected int height;
}

// Derived class
class Rectangle: Shape {
public int getArea() {
return (width * height);

Dr.G.S.Puranik 13
C# Notes

}
}

class RectangleTester {
static void Main(string[] args) {
Rectangle Rect = new Rectangle();

Rect.setWidth(5);
Rect.setHeight(7);

// Print the area of the object.


Console.WriteLine("Total area: {0}", Rect.getArea());
Console.ReadKey();
}
}
}

Output
Total area: 35
karthikeya Boyini
karthikeya Boyi

Difference between Abstract Class and Interface in C#

No. Abstract Class Interface

1 The special class which cannot be The interface enables us to determine the
instantiated is known as abstract class. functionality or functions but cannot
implement that.

2 Abstract classes have static members. Interface does not have static members.

3 They have a constructor. They don’t have a constructor.

4 It includes both a declaration and an It includes only a declaration.


explanation.

5 Here the performance is fast. Here the performance is slow.

7 A class has the liberty to only utilize a single Here a class has the liberty to utilize
abstract class. multiple interfaces.

Dr.G.S.Puranik 14
C# Notes

8 It is utilized to execute the core identity of It is utilized to execute the peripheral skills
class. of the class.

9 It includes methods, fields, constants, etc. It only includes methods .

10 Abstract class can be fully, partially or not Interfaces can be fully implemented
implemented.

Operator overloading in C# :
The ability to use the same operator (like arithmetic operator, +, -, *, /) to do various
operations is called Operator overloading.
Syntax:
public static return-type operator op(param-type1 operand1, param-type2 operand2)
{
// operations
}
 op: Operator for overloading.
 return-type: As the name suggested, this is the return type, and it might be
any type; whatever we choose,
the return-type value should be the same type as the class of the operator being
overloaded.
 param-type: It is a parameter value that we are passing through the method
using an operand.

Operator overloading in C# can be done using different forms of operators.

using System;
class Complex
{
private int x;
private int y;
public Complex()
{
}
public Complex(int i, int j)
{

Dr.G.S.Puranik 15
C# Notes

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;
temp.y = c1.y + c2.y;
return temp;
}
}
class MyComplex: Complex
{
private double x;
private double y;
public MyComplex(double i, double j)
{
x = i;
y = j;
}
public MyComplex()
{
}
public new void ShowXY()
{
Console.WriteLine("{0} {1}", x, y);
}
}

class MyClient
{
public static void Main()
{
MyComplex mc1 = new MyComplex(1.5, 2.5);
mc1.ShowXY();
MyComplex mc2 = new MyComplex(3.5, 4.5);
mc2.ShowXY();
MyComplex mc3 = new MyComplex();
//mc3 = mc1 + mc2;
//mc3.ShowXY();
}
}

Dr.G.S.Puranik 16
C# Notes

Boxing & UnBoxing in c#:

Boxing:
Boxing is the process of converting a value type to the object type or any
interface type
Ex:
int i = 123;
object o = i;

Unboxing in c#:
Unboxing is the reverse of boxing. It is the process of converting a reference type to
value type.
Ex:
o = 123;
i = (int)o; // unboxing

Example:
namespace BoxingUnboxingDemo
{
class Program
{
static void Main(string[] args)
{
int x = 10;
object y = x; //Boxing
int z = (int)y; //Unboxing
Console.WriteLine(z);
}
}
}

Delegates in c#

“A delegate is an object which refers to a method or you can say it is a reference type
variable that can hold a reference to the methods.”
 . It provides a way which tells which method is to be called when an event is
triggered.

 delegate is a reference to the method. It works like function pointer in C and C++
 It is objected-oriented, secured and type-safe than function pointer.
 For static method, delegate encapsulates method only. But for instance method, it
encapsulates method and instance both.

Syntax for delegate declaration :

delegate <return type> <delegate-name> <parameter list>

Ex: delegate int NumberChanger(int n);

Dr.G.S.Puranik 17
C# Notes

Ex:public delegate int MyDelegate (string s);

C# Delegate Example:
Let's see a simple example of delegate in C# which calls add() and mul() methods.

using System;
delegate int Calculator(int n);//declaring delegate

public class DelegateExample


{
static int number = 100;
public static int add(int n)
{
number = number + n;
return number;
}
public static int mul(int n)
{
number = number * n;
return number;
}
public static int getNumber()
{
return number;
}
public static void Main(string[] args)
{
Calculator c1 = new Calculator(add);//instantiating delegate
Calculator c2 = new Calculator(mul);
c1(20);//calling method using delegate
Console.WriteLine("After c1 delegate, Number is: " + getNumber());
c2(3);
Console.WriteLine("After c2 delegate, Number is: " + getNumber());

}
}
Output:

After c1 delegate, Number is: 120


After c2 delegate, Number is: 360

Example:

Dr.G.S.Puranik 18
C# Notes

using System;
delegate int Calc(int num);//declaring delegate

public class Example


{
static int n = 50;
public static int sub(int num)
{
n = n - num;
return n;
}
public static int mul(int num)
{
n = n * num;
return n;
}
public static int getnum()
{
return n;
}
public static void Main(string[] args)
{
Calc x = new Calc(sub);//instantiating delegate
Calc y = new Calc(mul);
x(10);//calling method using delegate
Console.WriteLine("After x delegate, Number is: " + getnum());
y(20);
Console.WriteLine("After y delegate, Number is: " + getnum());

}
}

Explanation:

In the above example, we are using the delegate in C# to call the sub() and mul()
methods.

Dr.G.S.Puranik 19
C# Notes

Events in c#:
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. For example, interrupts. Events are used for inter-process
communication.

using System;

namespace SampleApp {
public delegate string MyDel(string str);

class EventProgram {
event MyDel MyEvent;

public EventProgram() {
this.MyEvent += new MyDel(this.WelcomeUser);
}
public string WelcomeUser(string username) {
return "Welcome " + username;
}
static void Main(string[] args) {
EventProgram obj1 = new EventProgram();
string result = obj1.MyEvent("Tutorials Point");
Console.WriteLine(result);
}
}
}

Dr.G.S.Puranik 20

You might also like