UNIT-III
OOP’S IN C#
Class and Objects
Declaration of class
Generally, a class declaration contains only a keyword class, followed by
an identifier(name) of the class. But there are some optional attributes that can be used with
class declaration according to the application requirement. In general, class declarations can
include these components, in order:
Modifiers: A class can be public or internal etc. By default modifier of the class
is internal.
Keyword class: A class keyword is used to declare the type class.
Class Identifier: The variable of type class is provided. The identifier(or name of the
class) should begin with an initial letter which should be capitalized by convention.
Base class or Super class: The name of the class’s parent (superclass), if any, preceded by
the : (colon). This is optional.
Interfaces: A comma-separated list of interfaces implemented by the class, if any,
preceded by the : (colon). A class can implement more than one interface. This is optional.
Body: The class body is surrounded by { } (curly braces).
Example:
// declaring public class
public class Geeks
{
// field variable
public int a, b;
// member function or method
public void display()
{
Console.WriteLine(“Class & Objects in C#”);
}
}
Objects
It is a basic unit of Object-Oriented Programming and represents real-life entities. A typical C#
program creates many objects, which as you know, interact by invoking methods. An object
consists of :
State: It is represented by attributes of an object. It also reflects the properties of an object.
Behavior: It is represented by the methods of an object. It also reflects the response of an
object with other objects.
Identity: It gives a unique name to an object and enables one object to interact with other
objects.
Access Class Members using Object
We use the name of objects along with the . operator to access members of a class. For example,
using System;
namespace ClassObject {
class Dog {
string breed;
public void bark() {
Console.WriteLine("Bark Bark !!");
static void Main(string[] args) {
// create Dog object
Dog bullDog = new Dog();
// access breed of the Dog
bullDog.breed = "Bull Dog";
Console.WriteLine(bullDog.breed);
// access method of the Dog
bullDog.bark();
Console.ReadLine();
}
}
}
Output
Bull Dog
Bark Bark !!
Creating Multiple Objects of a Class
We can create multiple objects from the same class. For example,
using System;
namespace ClassObject {
class Employee {
string department;
static void Main(string[] args) {
// create Employee object
Employee sheeran = new Employee();
// set department for sheeran
sheeran.department = "Development";
Console.WriteLine("Sheeran: " + sheeran.department);
// create second object of Employee
Employee taylor = new Employee();
// set department for taylor
taylor.department = "Content Writing";
Console.WriteLine("Taylor: " + taylor.department);
Console.ReadLine();
}
}
}
Output
Sheeran: Development
Taylor: Content Writing
Creating objects in a different class
In C#, we can also create an object of a class in another class. For example,
For example,
using System;
namespace ClassObject {
class Employee {
public string name;
public void work(string work) {
Console.WriteLine("Work: " + work);
}
}
class EmployeeDrive {
static void Main(string[] args) {
// create Employee object
Employee e1= new Employee();
Console.WriteLine("Employee 1");
// set name of the Employee
e1.name="Gloria";
Console.WriteLine("Name: " + e1.name);
//call method of the Employee
e1.work("Coding");
Console.ReadLine();
}
}
}
Output
Employee 1
Name: Gloria
Work: Coding
Inheritance
One of the key concepts of Object Oriented Programming is nothing but inheritance. By
using the concept of inheritance, it is possible to create a new class from an existing one and add
new features to it.
In this case Derived class inherits public members of the Base class x,y and Method().The
objects of the Derived class can access these inherited members along with its own member z.
using System;
class Base
{
public int x = 10;
public int y = 20;
public void Method()
{
Console.WriteLine("Base Method");
}
}
class Derived : Base
{
public int z = 30;
}
class MyClient
{
public static void Main()
{
Derived d1 = new Derived();
Console.WriteLine("{0},{1},{2}",d1.x,d1.y,d1.z); // displays 10,20,30
d1.Method();// displays 'Base Method'
}
}
Inheritance & Data Members
We know all base class data members are inherited to the derived, but their accessibility
remains unchanged in the derived class. For example in the program given below
using System;
class Base
{
public int x = 10;
public int y = 20;
}
class Derived : Base
{
public int z = 30;
public void Sum()
{
int sum = x+y+z;
Console.WriteLine(sum);
}
}
class MyClient
{
public static void Main()
{
Derived d1 = new Derived();
d1.Sum();// displays '60'
}
}
Polymorphism:
Polymorphism is that in which we can perform a task in multiple forms or ways. It is
applied to the functions or methods. Polymorphism allows the object to decide which form of
the function to implement at compile-time as well as run-time.
C# Polymorphism
Polymorphism is one of the features provided by Object Oriented Programming.
Polymorphism simply means occurring in more than one form.
That is, the same entity (method or operator or object) can perform different operations in
different scenarios.
Example of Polymorphism
using System;
class Program
{
// method does not take any parameter
public void greet()
{
Console.WriteLine("Hello");
}
// method takes one string parameter
public void greet(string name)
{
Console.WriteLine("Hello " + name);
}
static void Main(string[] args)
{
Program p1 = new Program();
// calls method without any argument
p1.greet();
//calls method with an argument
p1.greet("Tim");
}
}
Output
Hello
Hello Tim
Multiple Inheritance:
In Multiple inheritance, one class can have more than one superclass and inherit
features from all its parent classes. As shown in the below diagram, class C inherits the
features of class A and B.
/ C# program to illustrate how to
// implement multiple class inheritance
// using interfaces
using System;
using System.Collections;
// Interface 1
interface GFG1 {
void languages();
}
// Parent class 1
class Geeks1 : GFG1 {
// Providing the implementation
// of languages() method
public void languages()
{
// Creating ArrayList
ArrayList My_list = new ArrayList();
// Adding elements in the
// My_list ArrayList
My_list.Add("C");
My_list.Add("C++");
My_list.Add("C#");
My_list.Add("Java");
Console.WriteLine("Languages provided by GeeksforGeeks:");
foreach(var elements in My_list)
{
Console.WriteLine(elements);
}
}
}
// Interface 2
interface GFG2 {
void courses();
}
// Parent class 2
class Geeks2 : GFG2 {
// Providing the implementation
// of courses() method
public void courses()
{
// Creating ArrayList
ArrayList My_list = new ArrayList();
// Adding elements in the
// My_list ArrayList
My_list.Add("System Design");
My_list.Add("Fork Python");
My_list.Add("Geeks Classes DSA");
My_list.Add("Fork Java");
Console.WriteLine("\nCourses provided by GeeksforGeeks:");
foreach(var elements in My_list)
{
Console.WriteLine(elements);
}
}
}
// Child class
class GeeksforGeeks : GFG1, GFG2 {
// Creating objects of Geeks1 and Geeks2 class
Geeks1 obj1 = new Geeks1();
Geeks2 obj2 = new Geeks2();
public void languages()
{
obj1.languages();
}
public void courses()
{
obj2.courses();
}
}
// Driver Class
public class GFG {
// Main method
static public void Main()
{
// Creating object of GeeksforGeeks class
GeeksforGeeks obj = new GeeksforGeeks();
obj.languages();
obj.courses();
}
}
Output:
Languages provided by GeeksforGeeks:
C
C++
C#
Java
Courses provided by GeeksforGeeks:
System Design
Fork Python
Geeks Classes DSA
Fork Java
Operator Overloading:
Operator overloading gives the ability to use the same operator to do various
operations.
C# operators when they are applied to user-defined data types.
It enables to make user-defined implementations of various operations where one or
both of the operands are of a user-defined class.
Only the predefined set of C# operators can be overloaded.
Operator overloading is basically the mechanism of providing a special meaning to an
ideal C# operator w.r.t. a user-defined data type such as structures or classes.
// C# program to illustrate the
// unary operator overloading
using System;
namespace Calculator {
class Calculator {
public int number1 , number2;
public Calculator(int num1 , int num2)
{
number1 = num1;
number2 = num2;
}
// Function to perform operation
// By changing sign of integers
public static Calculator operator -(Calculator c1)
{
c1.number1 = -c1.number1;
c1.number2 = -c1.number2;
return c1;
}
// Function to print the numbers
public void Print()
{
Console.WriteLine ("Number1 = " + number1);
Console.WriteLine ("Number2 = " + number2);
}
}
class EntryPoint
{
// Driver Code
static void Main(String []args)
{
// using overloaded - operator
// with the class object
Calculator calc = new Calculator(15, -25);
calc = -calc;
// To display the result
calc.Print();
}
}
}
Output :
Number1 = -15
Number2 = 25
Overloading Binary Operators
Binary Operators will work with two Operands. Examples of binary operators include
the Arithmetic Operators (+, -, *, /, %), Arithmetic Assignment operators (+=, -+, *=, /+,
%=) and Relational Operators etc. Overloading a binary operator is similar to overloading a
unary operator, except that a binary operator requires an additional parameter.
Syntax :
operator operator (object1, object2);
Here, second "operator" is a symbol that
denotes a binary operator.
operator + (a, b);
Example :
Input : 200, 40
Output : 240
Input : 300, 20
Output : 320
// C# program to illustrate the
// Binary Operator Overloading
using System;
namespace BinaryOverload {
class Calculator {
public int number = 0;
// no-argument constructor
public Calculator() {}
// parameterized constructor
public Calculator(int n)
{
number = n;
}
// Overloading of Binary "+" operator
public static Calculator operator + (Calculator Calc1,
Calculator Calc2)
{
Calculator Calc3 = new Calculator(0);
Calc3.number = Calc2.number + Calc1.number;
return Calc3;
}
// function to display result
public void display()
{
Console.WriteLine("{0}", number);
}
}
class CalNum {
// Driver Code
static void Main(string[] args)
{
Calculator num1 = new Calculator(200);
Calculator num2 = new Calculator(40);
Calculator num3 = new Calculator();
num3 = num1 + num2;
num1.display(); // Displays 200
num2.display(); // Displays 40
num3.display(); // Displays 240
}
}
}
Output :
200
40
240
Benefits of Operator Overloading :
Operator Overloading provides additional capabilities to C# operators when they are
applied to user-defined data types.
Operators may be considered as functions internal to the compiler.
Delegates and Events:
Delegates in C# provide a way to define and execute callbacks.
Their flexibility allows you to define the exact signature of the callback, and that information
becomes part of the delegate type itself.
Delegates are type-safe, object-oriented, and secure.
Delegates have the following characteristics:
Delegates are derived from the System.MulticastDelegate class.
They have a signature and a return type. A function that is added to delegates must be
compatible with this signature.
Delegates can point to either static or instance methods.
Once a delegate object has been created, it may invoke the methods it points to at runtime.
Delegates can call methods synchronously and asynchronously.
A delegate can be defined as a delegate type. Its definition must be similar to the function
signature.
A delegate can be defined in a namespace and within a class.
A delegate cannot be used as a data member of a class or local variable within a method.
Delegates Sample Program
The delegate implementation can cause a great deal of confusion when encountered the first
time. Thus, it is a great idea to get an understanding by creating this sample program:
using System;
namespace Delegates
{
// Delegate Definition
public delegate int operation(int x, int y);
class Program
{
// Method that is passes as an Argument
// It has same signature as Delegates
static int Addition(int a, int b)
{
return a + b;
}
static void Main(string[] args)
{
// Delegate instantiation
operation obj = new operation(Program.Addition);
// output
Console.WriteLine("Addition is={0}",obj(23,27));
Console.ReadLine();
}
}
}
Array of Delegates
Creating an array of delegates is similar to declaring an array of any type. The following
example has a couple of static methods to perform specific math-related operations. Then you
use delegates to call these methods.
using System;
namespace Delegates
{
public class Operation
{
public static void Add(int a, int b)
{
Console.WriteLine("Addition={0}",a + b);
}
public static void Multiple(int a, int b)
{
Console.WriteLine("Multiply={0}", a * b);
}
}
class Program
{
delegate void DelOp(int x, int y);
static void Main(string[] args)
{
// Delegate instantiation
DelOp[] obj =
{
new DelOp(Operation.Add),
new DelOp(Operation.Multiple)
};
for (int i = 0; i < obj.Length; i++)
{
obj[i](2, 5);
obj[i](8, 5);
obj[i](4, 6);
}
Console.ReadLine();
}
}
}
Events
The applications and windows communicate via predefined messages.
These messages contain various information to determine window and application actions.
The .NET considers these messages as an event.
You will handle the corresponding event if you need to react to a specific incoming message. For
instance, when a button is clicked on a form, Windows sends a WM_MOUSECLICK message to
the button message handler.
The syntax for the event definition should be as in the following:
Accessibility event delegatename eventname;
using System;
namespace Delegates
{
public delegate void DelEventHandler();
class Program
{
public static event DelEventHandler add;
static void Main(string[] args)
{
add += new DelEventHandler(USA);
add += new DelEventHandler(India);
add += new DelEventHandler(England);
add.Invoke();
Console.ReadLine();
}
static void USA()
{
Console.WriteLine("USA");
}
static void India()
{
Console.WriteLine("India");
}
static void England()
{
Console.WriteLine("England");
}
}
}
Managing Console I/O Operations:
Contents
The Console Class
Managing Console I/O Operations
Console.OpenStandardInput Method()
Console.OpenStandardOutput Method()
Console.Read Method()
Console.ReadLine Method()
Console.Write Method(Boolean)
Console.Write Method(String)
The Console Class
To allow console input/output operations, C# provides, C# provides a console class. The
Console class provides basic input and output support for applications that read from and write
characters to the console. The standard input, output, and error streams are represented by
properties, and are automatically associated with the console when the application starts.
Application can redirected these properties to other streams; for example, streams associated
with fies instead of the console.
using System;
class ConsoleTest
{
public static void Main()
{
Console.Write("Hello");
Console.WriteLine("World");
Console.Write("What is Your Name");
String name = Console.ReadLine();
Console.Write("Hello, ");
Console.Write(name);
Console.WriteLine(" ! ");
}
}
Console.OpenStandardInput Method()
This method acquires the standard input stream. The code given below shows this. This
method can be used to reacquire the standard input stream after it has been changed by the
SetIn method. Consider the following code snippet for illustration.
The following code sample illustrates the user of OpenStandardInput:
public class Decoder
{
public static void Main()
{
Stream inputStream = Console.OpenStandardInput();
byte [] bytes = new byte[100];
Console.WriteLine("To decode, type or paste the UTF7 encoded string and press enter:");
Console.WriteLine("(Example: \"M+APw-nchen ist wundervoll\")");
int outputLength = inputStream.Read(bytes, 0 ,100);
char [] chars = Encoding.UTF7.GetChars(bytes, 0 , outputLenght);
Console.WriteLine("Decoded String:");
Console.WriteLine(new string(chars));
}
}
Console.OpenStandardOutput Method()
The method acquires the standard output stream. This method can be used to reqcquire the
standard output stream after it has been changed by the SetOut method. Consider the following
code snippet for illustration.
public class InsertTabs
{
private const int tabSize = 4;
private const string usageText = "Usage: INSERTTABS inputfile.txt outputfile.txt";
public static int Main(String[] args)
{
StreamWriter writer = null;
if (args.Length < 2)
{
Console.WriteLine(usageTextt);
return 1;
}
try
{
write = new StramWriter(args[1]);
Console.SetOut(writer);
Console.SetIn(new StreamReader(args[0]));
}
catch(IOException e)
{
TextWriter errorWriter = Console.Error;
errorWriter.WriteLine(e.Message);
errorWriter.WriteLine(usageText);
return 1;
}
string line;
while((line = Console.ReadLine())!= null)
{
string newLine = line.Replace(("").PadRight(tabSize,'),"\t");
Console.WriteLine(newLine);
}
writer.Close();
//Recover the standard output stream so that a
// Completion message can be displayed.
StreamWriter standardOutput = new StreamWriter(Console.OpenStandardOutput());
standardOutput.AutoFlush = true;
Console.SetOut(standardOutput);
Console.WriteLine("INSERTTABS has completed the processing of (0).", args[0]);
return 0;
}
}
Console.Read Method()
This method reads the next character from the standard input stream. It returns the next
character from the input stream, or negative one (-1) if no more characters are available. This
method will not return until the read operation is terminated; for example by the user pressing
the enter key. If data is available, the input stream contains what the user entered, suffixed with
the environment dependent newline character. Consider the following for illustration.
int i;
char c;
while(true)
{
i = Console.Read();
if (i == 1)
break;
c = (char) l;
Console.WriteLIne("Echo: )0)",c);
}
Console.WriteLine("Done");
return 0;
Console.ReadLine Method()
This method reads the next line of characters from the standard input stream. It returns the
next line from the input stream, or a null reference if no more charcters are available. A line is
defined as a sequence of characters followed by a carriage return (hexadecimal 0x000d), a line
feed (hexadecimal 0x000a). The returned string does not contain the termination character(s).
Consider the following code for illustration.
public class InsertTabs
{
private const int tabSize = 4;
private const string usageText = "Usage: INSERTTABS inputfile.txt outputfile.txt";
public static int Main(String[] args)
{
StreamWriter writer = null;
if (args.Length < 2)
{
Console.WriteLine(usageTextt);
return 1;
}
try
{
write = new StramWriter(args[1]);
Console.SetOut(writer);
Console.SetIn(new StreamReader(args[0]));
}
catch(IOException e)
{
TextWriter errorWriter = Console.Error;
errorWriter.WriteLine(e.Message);
errorWriter.WriteLine(usageText);
return 1;
}
string line;
while((line = Console.ReadLine())!= null)
{
string newLine = line.Replace(("").PadRight(tabSize,'),"\t");
Console.WriteLine(newLine);
}
writer.Close();
//Recover the standard output stream so that a
// Completion message can be displayed.
StreamWriter standardOutput = new StreamWriter(Console.OpenStandardOutput());
standardOutput.AutoFlush = true;
Console.SetOut(standardOutput);
Console.WriteLine("INSERTTABS has completed the processing of (0).", args[0]);
return 0;
}
}
Console.Write Method(Boolean)
This method writes the text representation of the specified Boolean value to the standard
output stream. The text representation of value is produced by calling Boolean.Tostring.
Consdier the following code for illustration.
public class FormatConverter
{
public static void Main(string[] args)
{
string lineInput;
while((lineInput = Console.ReadLine()) != null)
{
bool isFirstField = true;
foreach(string item in fields)
{
if (isFirstField)
isFirstField = false;
else
Console.Write(',');
try
{
Console.Write(Convert.ToByte(Convert.ToBoolean(item)));
}
catch(FormatException)
{
Console.Write(item);
}
}
Console.WriteLine();
}
}
}
Console.Write Method(String)
This method writes the specified string value to the standard output stream. If value is a null
reference, nothing is written to the standard output stream. Consider the following code for
illustration.
public class FormatConverter
{
public static void Main(string[] args)
{
string lineInput;
while((lineInput = Console.ReadLine()) != null)
{
bool isFirstField = true;
foreach(string item in fields)
{
if (isFirstField)
isFirstField = false;
else
Console.Write(',');
try
{
Console.Write(Convert.ToByte(Convert.ToBoolean(item)));
}
catch(FormatException)
{
Console.Write(item);
}
}
Console.WriteLine();
}
}
}
Managing Exception and Errors:
//C#: Exception Handling
using System;
class MyClient
{
public static void Main()
{
int x = 0;
int div = 0;
try
{
div = 100/x;
Console.WriteLine("Not executed line");
}
catch(DivideByZeroException)
{
Console.WriteLine("Exception occured");
}
finally
{
Console.WriteLine("Finally Block");
}
Console.WriteLine($"Result is {div}");
}
}
/C#: Exception Handling: Handling all exceptions
using System;
class MyClient
{
public static void Main()
{
int x = 0;
int div = 0;
try
{
div = 100 / x;
Console.WriteLine("Not executed line");
}
catch
{
Console.WriteLine("oException");
}
Console.WriteLine($"Result is {div}");
}
}
C#
The following program handles all exceptions with an Exception object.
//C#: Exception Handling: Handling all exceptions
using System;
class MyClient
{
public static void Main()
{
int x = 0;
int div = 0;
try
{
div = 100 / x;
Console.WriteLine("Not executed line");
}
catch (Exception)
{
Console.WriteLine("oException");
}
Console.WriteLine($"Result is {div}");
}
}
C#
Throwing an Exception in C#
In C#, it is possible to throw an exception programmatically. The 'throw' keyword is used for this
purpose. The general form of throwing an exception is as follows.
throw exception_obj;
C#
For example, the following statement throws an ArgumentException explicitly.
throw new ArgumentException("Exception");
//C#: Exception Handling:
using System;
class MyClient
{
public static void Main()
{
try
{
throw new DivideByZeroException("Invalid Division");
}
catch (DivideByZeroException)
{
Console.WriteLine("Exception");
}
Console.WriteLine("LAST STATEMENT");
}
}
The ApplicationException is thrown by a user program rather than the runtime. The
SystemException includes the ExecutionEngineException, StaclOverFlowException, etc.
The following table provides some of the predefined exception classes derived from the
Sytem.SystemException class −
Sr.No. Exception Class & Description
1
System.IO.IOException
Handles I/O errors.
2
System.IndexOutOfRangeException
Handles errors generated when a method refers to an array index out of range.
3
System.ArrayTypeMismatchException
Handles errors generated when type is mismatched with the array type.
4
System.NullReferenceException
Handles errors generated from referencing a null object.
5
System.DivideByZeroException
Handles errors generated from dividing a dividend with zero.
6
System.InvalidCastException
Handles errors generated during typecasting.
7
System.OutOfMemoryException
Handles errors generated from insufficient free memory.
8
System.StackOverflowException
Handles errors generated from stack overflow.
Types of Exceptions:
Exception and SystemException.
ApplicationException.
InvalidOperationException.
ArgumentException, ArgumentNullException, and ArgumentOutOfRangeException.
NullReferenceException, IndexOutOfRangeException, and AccessViolationException.
StackOverflowException.
OutOfMemoryException.
What are the 3 types of exceptions?
There are three types of exception—the checked exception, the error and the runtime exception.
What are the four kinds of exceptions?
4) if the exception interrupted a user program, and then returns control to the interrupted
program. Exceptions can be divided into four classes: interrupts, traps, faults, and
aborts.
What are the main exception types?
Exceptions can be categorized into two ways:
Built-in Exceptions. Checked Exception. Unchecked Exception.
User-Defined Exceptions.