0% found this document useful (0 votes)
16 views20 pages

Unit 3 New

The document provides an overview of Object-Oriented Programming (OOP) in C#, covering key concepts such as classes, objects, inheritance, method and operator overloading, and constructors. It explains the advantages of OOP over procedural programming, including code reusability and maintainability. Additionally, the document includes examples demonstrating the implementation of these concepts in C#.

Uploaded by

bhatt navtej
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)
16 views20 pages

Unit 3 New

The document provides an overview of Object-Oriented Programming (OOP) in C#, covering key concepts such as classes, objects, inheritance, method and operator overloading, and constructors. It explains the advantages of OOP over procedural programming, including code reusability and maintainability. Additionally, the document includes examples demonstrating the implementation of these concepts in C#.

Uploaded by

bhatt navtej
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/ 20

21-03-2024

Object Oriented Programming in C#


Unit - 3

Contents
 Classes and Structure,
 Construction and Disposal of object,
 Inheritance,
 Method Overloading,
 Operator Overloading,
 Interfaces,
 Collections,
 Indexers,
 Delegates and Events

1
21-03-2024

What is OOP?
 OOP stands for Object-Oriented Programming.

 Procedural programming is about writing procedures or methods that perform


operations on the data, while object-oriented programming is about creating
objects that contain both data and methods.

 Object-oriented programming has several advantages over procedural


programming:

 OOP is faster and easier to execute


 OOP provides a clear structure for the programs
 OOP helps to keep the C# code DRY "Don't Repeat Yourself", and makes the code
easier to maintain, modify and debug
 OOP makes it possible to create full reusable applications with less code and
shorter development time

What are Classes and Objects?


 Classes and objects are the two main aspects of object-oriented
programming.

 In C#, Object is a real world entity, for example, chair, car, pen, mobile,
laptop etc.
 In other words, object is an entity that has state and behavior. Here, state
means data and behavior means functionality.

2
21-03-2024

 Object is a runtime entity, it is created at runtime.

 Object is an instance of a class. All the members of the class can be accessed
through object.

 Let's see an example to create object using new keyword.

 Student s1 = new Student();//creating an object of Student


 In this example, Student is the type and s1 is the reference variable that
refers to the instance of Student class. The new keyword allocates memory at
runtime.

C# Class
 In C#, class is a group of similar objects. It is a template from which objects
are created. It can have fields, methods, constructors etc.

 Let's see an example of C# class that has two fields only.

 public class Student


 {
 int id;//field or data member
 String name;//field or data member
 }

3
21-03-2024

C# Object and Class Example


 using System;
 public class Student
 {
 int id;//data member (also instance variable)
 String name;//data member(also instance variable)

 public static void Main(string[] args)


 {
 Student s1 = new Student();//creating an object of Student
 s1.id = 101;
 s1.name = “Hiral";
 Console.WriteLine(s1.id);
 Console.WriteLine(s1.name);
 }
 }
 Output:
 101
 Hiral

C# Class Example 2: Having Main() in another


class
 using System;
 public class Student
 {
 public int id;
 public String name;
 }
 class TestStudent{
 public static void Main(string[] args)
 {
 Student s1 = new Student();
 s1.id = 101;
 s1.name = “Hiral";
 Console.WriteLine(s1.id);
 Console.WriteLine(s1.name);
 }
 }
 Output:
 101
 Hiral

4
21-03-2024

C# Class Example 3: Initialize and Display data through method


using System;
public class Student
{
public int id;
public String name;
public void insert(int i, String n)
{
id = i;
name = n;
}
public void display()
{
Console.WriteLine(id + " " + name);
}
}
class TestStudent{
public static void Main(string[] args)
{
Student s1 = new Student();
Student s2 = new Student();
s1.insert(101, "Ajeet");
s2.insert(102, "Tom");
s1.display();
s2.display();
}
}
Output:
101 Ajeet
102 Tom

C# Constructor
 In C#, constructor is a special method which is invoked automatically at the
time of object creation. It is used to initialize the data members of new
object generally. The constructor in C# has the same name as class or struct.

 There can be two types of constructors in C#.

 Default constructor
 Parameterized constructor

10

5
21-03-2024

C# Default Constructor
 A constructor which has no argument is known as default constructor. It is invoked at the
time of creating object.
 C# Default Constructor Example: Having Main() within class
 using System;
 public class Employee
 {
 public Employee()
 {
 Console.WriteLine("Default Constructor Invoked");
 }
 public static void Main(string[] args)
 {
 Employee e1 = new Employee();
 Employee e2 = new Employee();
 }
 }
 Output:

 Default Constructor Invoked


 Default Constructor Invoked

11

C# Default Constructor Example: Having


Main() in another class
 Let's see another example of default constructor where we are having Main() method in another class.
 using System;
 public class Employee
 {
 public Employee()
 {
 Console.WriteLine("Default Constructor Invoked");
 }
 }
 class TestEmployee{
 public static void Main(string[] args)
 {
 Employee e1 = new Employee();
 Employee e2 = new Employee();
 }
 }
 Output:
 Default Constructor Invoked
 Default Constructor Invoked

12

6
21-03-2024

C# Parameterized Constructor
 A constructor which has parameters is called
parameterized constructor. It is used to provide
different values to distinct objects. class TestEmployee
 using System;
{
 public class Employee
public static void Main(string[] args)
 {
 public int id; {
 public String name; Employee e1 = new Employee(101, "Sonoo", 890000f);
 public float salary; Employee e2 = new Employee(102, "Mahesh", 490000f);
 public Employee(int i, String n,float s)
e1.display();
 {
e2.display();
 id = i;
 name = n; }
 salary = s; }
 } Output:
 public void display()
 {
101 Sonoo 890000
 Console.WriteLine(id + " " + name+" "+salary);
102 Mahesh 490000
 }
 }

13

C# Destructor
 A destructor works opposite to constructor, It destructs the objects of classes.
It can be defined only once in a class. Like constructors, it is invoked
automatically.
 Note: C# destructor cannot have parameters.

14

7
21-03-2024

C# Constructor and Destructor Example


 Let's see an example of constructor and destructor in C# which is called automatically.
 using System;
 public class Employee
 {
 public Employee()
Output:
 {
 Console.WriteLine("Constructor Invoked");
Constructor Invoked
 }
Constructor Invoked
 ~Employee()
Destructor Invoked
 {
Destructor Invoked
 Console.WriteLine("Destructor Invoked");
 }
 }
 class TestEmployee{
 public static void Main(string[] args)
 {
 Employee e1 = new Employee();
 Employee e2 = new Employee();

 }
 }

15

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.

16

8
21-03-2024

C# Single Level Inheritance Example:


Inheriting Fields
 When one class inherits another class, it is known as single level inheritance.

 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

17

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...

18

9
21-03-2024

C# Multi Level Inheritance Example


 When one class inherits another class which is class TestInheritance2{
further inherited by another class, it is known public static void Main(string[]
as multi level inheritance in C#. Inheritance is
transitive so the last derived class acquires all args)
the members of all its base classes. {
 Let's see the example of multi level inheritance BabyDog d1 = new BabyDog();
in C#.
d1.eat();
 using System; d1.bark();
 public class Animal d1.weep();
 {
 public void eat() { }
Console.WriteLine("Eating..."); } }
 } Output:
 public class Dog: Animal
 { Eating...
 public void bark() { Barking...
Console.WriteLine("Barking..."); }
 } Weeping...

 public class BabyDog : Dog


 {
 public void weep() {
Console.WriteLine("Weeping..."); }
 }

19

C# Method Overloading
 Having two or more methods with same name but different in parameters, is
known as method overloading in C#.

 The advantage of method overloading is that it increases the readability of


the program because you don't need to use different names for same action.

 You can perform method overloading in C# by two ways:

 By changing number of arguments


 By changing data type of the arguments

20

10
21-03-2024

C# Method Overloading Example: By changing no. of arguments


 using System;

 public class Cal{

 public static int add(int a,int b){

 return a + b;

 }

 public static int add(int a, int b, int c)

 {

 return a + b + c;

 }

 }

 public class TestMemberOverloading

 {

 public static void Main()

 {

 Console.WriteLine(Cal.add(12, 23));

 Console.WriteLine(Cal.add(12, 23, 25));

 }

 }

 Output:

 35

 60
21

C# Member Overloading Example: By changing data type of


arguments
 Let's see the another example of method overloading where we are changing data type of arguments.
 using System;
 public class Cal{
 public int add(int a, int b){
 return a + b;
 }
 public float add(float a, float b)
 {
 return a + b;
 }
 }
 public class TestMemberOverloading
 {
 public static void Main()
 {
 Cal c=new Cal();
 Int s1=Cal.add(12, 23);
 Int s2=Cal.add(12.4f,21.3f);
 Console.WriteLine();
 Console.WriteLine();
 }
 }

22

11
21-03-2024

Operator Overloading In C#
 In C#, a special function called operator function is used for overloading
purpose. These special function or method must be public and static. They
can take only value arguments. The ref and out parameters are not allowed
as arguments to operator functions. The general form of an operator function
is as follows.

 public static return_type operator op (argument list)


 Where the op is the operator to be overloaded and operator is the required
keyword. For overloading the unary operators, there is only one argument and
for overloading a binary operator there are two arguments. Remember that at
least one of the arguments must be a user-defined type such as class or struct
type.

23

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 a overloaded binary operator is as follows.

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


 {
 //Statements
 }

24

12
21-03-2024

 class Complex
 {
 private int x;
 private int y;
class MyClient
 public Complex() {
{
 } public static void Main()
 public Complex(int i, int j) {
 { Complex c1 = new Complex(10, 20);
 x = i; c1.ShowXY(); // displays 10 & 20
 y = j; Complex c2 = new Complex(20, 30);
 } c2.ShowXY(); // displays 20 & 30
 public void ShowXY() Complex c3 = new Complex();
 { c3 = c1 + c2;
 Console.WriteLine("{0} {1}", x, y); c3.ShowXY(); // dislplays 30 & 50
 } }
 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;
 }
 }

25

Example 2
 class Rectangle
 {
public static Rectangle operator + (Rectangle b, Rectangle c)
 private int length;
{
 private int breadth;
Rectangle r = new Rectangle();
 private int height; r.length = b.length + c.length;
 r.breadth = b.breadth + c.breadth;
 public Rectangle() { } //default r.height = b.height + c.height;
constructor
return r;

}
 public Rectangle(int l,int b, int h)
//parameterized constructor
 {
class Program{
public static void Main()
 length=l;
{
 breadth=b;
Rectangle r1=new Rectangle(10,15,20);
 height=h;
Rectangle r2=new Rectangle(15,25,30);
 } Rectangle r3 = new Rectangle();
 public void display() r3=r1+r2;
 { r3.display();
 Console.WriteLine(length); }
Console.WriteLine(breadth);
Console.WriteLine(height); }
 }

26

13
21-03-2024

C# Interface
 Interface in C# is a blueprint of a class. It is like abstract class because all the
methods which are declared inside the interface are abstract methods. It
cannot have method body and cannot be instantiated.

 It is used to achieve multiple inheritance which can't be achieved by class. It


is used to achieve fully abstraction because it cannot have method body.
 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.

27

C# interface example
 Let's see the example of interface in C# which has
draw() method. Its implementation is provided by two public class TestInterface
classes: Rectangle and Circle. {
 using System;
public static void Main()
 public interface Drawable
 { {
 void draw(); Rectangle d = new Rectangle();
 } d.draw();
 public class Rectangle : Drawable Circle c = new Circle();
 { c.draw();
 public void draw() }
 { }
 Console.WriteLine("drawing rectangle...");
Output:
 }
 }
 public class Circle : Drawable drawing ractangle...
 { drawing circle...
 public void draw()
 {
 Console.WriteLine("drawing circle...");
 }
 }

28

14
21-03-2024

Collections
 Collection classes are specialized classes for data storage and
retrieval. These classes provide support for stacks, queues, lists, and
hash tables. Most collection classes implement the same interfaces.

 Collection classes serve various purposes, such as allocating memory


dynamically to elements and accessing a list of items on the basis of
an index etc. These classes create collections of objects of the Object
class, which is the base class for all data types in C#.

29

Example collections: Arraylist


 using System; Console.WriteLine("Capacity: {0} ",
 using System.Collections; al.Capacity);
Console.WriteLine("Count: {0}",
 namespace CollectionApplication { al.Count);
 class Program { Console.Write("Content: ");
 static void Main(string[] args) { foreach (int i in al) {
 ArrayList al = new ArrayList(); Console.Write(i + " ");

}
 Console.WriteLine("Adding
Console.WriteLine();
some numbers:"); Console.Write("Sorted Content: ");
 al.Add (45); al.Sort();
 al.Add (78); foreach (int i in al) {
 al.Add(33); Console.Write(i + " ");
 al.Add(56);
}
Console.WriteLine();
 al.Add(12);
Console.ReadKey(); } }}
 al.Add(23);
 al.Add(9);
Output
Adding some numbers:
Capacity: 8
Count: 7
Content: 45 78 33 56 12 23 9
Content: 9 12 23 33 45 56 78

30

15
21-03-2024

Stack
 It represents a last-in, first out collection of object. It is used when you need
a last-in, first-out access of items. When you add an item in the list, it is
called pushing the item and when you remove it, it is called popping the
item.

31

 using System; Console.WriteLine("The next poppable value in stack: {0}", st.Peek());


 using System.Collections; Console.WriteLine("Current stack: ");
 namespace CollectionsApplication {
 class Program {
foreach (char c in st) {
Console.Write(c + " ");
 static void Main(string[] args) {
}
 Stack st = new Stack();
 st.Push('A'); Console.WriteLine();
 st.Push('M'); Console.WriteLine("Removing values ");
st.Pop();
 st.Push('G');
st.Pop();
 st.Push('W'); st.Pop();
 Console.WriteLine("Current stack:
"); Console.WriteLine("Current stack: ");
 foreach (char c in st) { foreach (char c in st) {
 Console.Write(c + " "); Console.Write(c + " ");
 } }
}
 Console.WriteLine();
}
 st.Push('V'); }
 st.Push('H');

32

16
21-03-2024

Queue
 It represents a first-in, first out collection of object. It is used when you need
a first-in, first-out access of items. When you add an item in the list, it is
called enqueue, and when you remove an item, it is called deque.

33

 using System;
Console.WriteLine();
 using System.Collections;
Console.WriteLine("Removing some values ");
char ch = (char)q.Dequeue();
 namespace CollectionsApplication { Console.WriteLine("The removed value: {0}", ch);
ch = (char)q.Dequeue();
 class Program {
Console.WriteLine("The removed value: {0}", ch);
 static void Main(string[] args) {
 Queue q = new Queue(); Console.ReadKey();
}
 q.Enqueue('A'); }
 q.Enqueue('M'); }
 q.Enqueue('G'); When the above code is compiled and executed, it produces the
following result −
 q.Enqueue('W');
 Current queue:
 Console.WriteLine("Current queue: "); AM G W
Current queue:
 foreach (char c in q) Console.Write(c + " "); AM G WV H
 Console.WriteLine(); Removing values
 q.Enqueue('V'); The removed value: A
The removed value: M
 q.Enqueue('H');
 Console.WriteLine("Current queue: ");
 foreach (char c in q) Console.Write(c + " ");

34

17
21-03-2024

Delegates
 C# delegates are similar to pointers to functions, in C or C++. A delegate is a reference
type variable that holds the reference to a method. The reference can be changed at
runtime.
 Delegates are especially used for implementing events and the call-back methods. All
delegates are implicitly derived from the System.Delegate class.

 Declaring Delegates
 Delegate declaration determines the methods that can be referenced by the delegate.
A delegate can refer to a method, which has the same signature as that of the
delegate.

35

Syntax for delegate declaration


 For example, consider a delegate −
 public delegate int MyDelegate (string s);
 The preceding delegate can be used to reference any method that has a
single string parameter and returns an int type variable.

 Syntax for delegate declaration is −


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

36

18
21-03-2024

Instantiating Delegates
Once a delegate type is declared, a delegate object must be created with the
new keyword and be associated with a particular method.
When creating a delegate, the argument passed to the new expression is written
similar to a method call, but without the arguments to the method. For example

public delegate void printString(string s);


...
printString ps1 = new printString(WriteToScreen);
printString ps2 = new printString(WriteToFile);

37

public delegate void Delegateeg(); class Program


{
public class TestDelegate static void Main(string[] args)
{
{
//Declaration
//Creating Delegates with no TestDelegate tl = new
parameters and no return type. TestDelegate();
public void fun1() Delegateeg f1 = tl.fun1;
{ Delegateeg f2 = tl.fun2;
Console.WriteLine("Function 1"); Delegateeg f3= tl.fun3;
} f1();
public void fun2() f2();
{
f3();
Console.WriteLine("Function 2");
} Console.ReadLine();
public void fun3() }
{ }
Console.WriteLine("Function 3");
}
}

38

19
21-03-2024

Following example demonstrates declaration, instantiation, and use of a delegate that can
be used to reference methods that take an integer parameter and returns an integer value.
static void Main(string[] args) {
using System;
//create delegate instances
NumberChanger nc1 = new
delegate int NumberChanger(int n);
NumberChanger(AddNum);
namespace DelegateAppl {
NumberChanger nc2 = new
NumberChanger(MultNum);
class TestDelegate {
static int num = 10;
//calling the methods using the delegate objects
nc1(25);
public static int AddNum(int p) {
Console.WriteLine("Value of Num: {0}", getNum());
num += p;
nc2(5);
return num;
Console.WriteLine("Value of Num: {0}", getNum());
}
Console.ReadKey();
public static int MultNum(int q) {
}
num *= q;
}
return num;
}
}
When the above code is compiled and executed, it
public static int getNum() {
produces the following result −
return num;
}
Value of Num: 35
Value of Num: 175

39

20

You might also like