OOP Concepts in C#

Download as pdf or txt
Download as pdf or txt
You are on page 1of 22

National Institute of Business Management-Galle

Object Oriented Programming in C#

Submitted by:
DCSD-G-17.1F-025 Subhashana K G R

Submitted to:
Mr.Sujeewa Sampath Gamage

Date of Submission
10.09.2017

National Institute of Business Management


1
Acknowledgements

For the first I extend my sincere gratitude’s to Mr. Sujeewa Sampath Gamage who
conducted we to on this work of report made me knowledgeable to continue the fast and to
complete it successfully. Then I’d like to express my heartfelt gratitude’s to Mrs.Chami
Muthugamage and my friends for help to inform more details and also thankfully give my
regards to my parents who were behind me in all my success and also my colleagues who and
all the other personalities who gave their fullest corporation to make this report success.

National Institute of Business Management


2
Table of Contents

Acknowledgements ........................................................................................................................... 2
1. Introduction ............................................................................................................................... 4
1.1. Class................................................................................................................................... 5
1.2. Object ................................................................................................................................ 5
2. File Handling .............................................................................................................................. 6
2.1. Uses of File Handling .......................................................................................................... 7
3. Exception Handling .................................................................................................................... 9
3.1. The try block .................................................................................................................... 10
3.2. Exception Nesting ................................................................................................................ 10
3.3. The catch block ................................................................................................................ 10
3.4. The finally block ............................................................................................................... 14
3.5. Exceptions and Custom Messages .................................................................................... 16
Throwing an Exception .................................................................................................................... 17
3.6. The Exception Class ............................................................................................................. 18
3.7. The Hierarchy of Exception Class ........................................................................................ 18
4. Delegates................................................................................................................................. 20
References ...................................................................................................................................... 22

National Institute of Business Management


3
1. Introduction

Object-oriented programming (OOP) is a programming language model organized


around "objects" rather than "actions" and data rather than logic. Historically, a program has
been viewed as a logical procedure that takes input data, processes it, and produces output data.
The first step in OOP is to identify all the objects you want to manipulate and how they relate
to each other, an exercise often known as data modeling. Once you've identified an object, you
generalize it as a class of objects and define the kind of data it contains and any logic sequences
that can manipulate it. Each distinct logic sequence is known as a method. A real instance of a
class is called an “object” or an “instance of a class”. The object or class instance is what you
run in the computer. Its methods provide computer instructions and the class object
characteristics provide relevant data. You communicate with objects - and they communicate
with each other. Important features with OOP are:

 C# provides full support for object-oriented programming including encapsulation,


inheritance, and polymorphism.
 Encapsulation means that a group of related properties, methods, and other members
are treated as a single unit or object.
 Inheritance describes the ability to create new classes based on an existing class.
 Polymorphism means that you can have multiple classes that can be used
interchangeably, even though each class implements the same properties or methods
in different ways.

 OOP has the following important features.

National Institute of Business Management


4
1.1. Class

A class is the core of any modern Object Oriented Programming language such as C#.

In OOP languages it is mandatory to create a class for representing data.

A class is a blueprint of an object that contains variables for storing data and functions to
perform operations on the data.

A class will not occupy any memory space and hence it is only a logical representation of
data.

To create a class, you simply use the keyword "class" followed by the class name:

1. class Employee
2. {
3.
4. }

1.2. Object

Objects are the basic run-time entities of an object oriented system. They may represent a
person, a place or any item that the program must handle. An object is a software bundle of
related variable and methods. An object is an instance of a class. A class will not occupy any
memory space. Hence to work with the data represented by the class you must create a variable
for the class, that is called an object. When an object is created using the new operator, memory
is allocated for the class in the heap, the object is called an instance and its starting address will
be stored in the object in stack memory.
When an object is created without the new operator, memory will not be allocated in the heap,
in other words an instance will not be created and the object in the stack contains the value null.

When an object contains null, then it is not possible to access the members of the class using
that object.

1. class Employee
2. {
3.
4. }

Syntax to create an object of class Employee:

1. Employee objEmp = new Employee();

National Institute of Business Management


5
2. File Handling
The .Net framework provides a few basic classes for creating, reading and writing to files on
the secondary storage and for retrieving file system information. They are located in the
System.IO namespace and used both in desktop applications and the web applications.
We can categorise file handling jobs in two parts –

1. Implementing File Input and Output Operations – this involves reading and
writing from and to a file saved on the disk. When a file is opened, the data from
the file is stored into a sequence of bytes called Stream. Your program uses this
stream to retrieve or store data. C# provides a FileStream class and as well as
StreamReader and StreamWriter classes to read from and write to a byte stream.
Again, data could be binary data, instead of sequence of bytes. For that we have
BinaryReader and BinaryWriter classes.

2. Working with the File System – this involves accessing the files and directory
present in your system and performing typical file system operations such as
copying files and creating directories. System.IO namespace provides classes
working with the file system of a machine as seen by the server. These classes
could be categorised into two parts:

 Directory and File classes: these classes provides the static


methods that allow retrieving information about any files and
directories
 DirectoryInfo and FileInfo classes: these classes use similar
instance methods and properties.

Both group of classes provide similar methods and properties, the difference being – you need
to have a DirectoryInfo or FileInfo object to use the methods of second group of classes,
whereas the static methods of first group of classes are always available.

National Institute of Business Management


6
2.1. Uses of File Handling

As a C# programmer, several times you need to save information on a disk. Because of this file
handling you don’t need to get database everywhere to save information.

Example:

In the .NET framework, the System.IO namespace is the region of the base class libraries
devoted to file based input and output services. Like any namespace, the System.IO namespace
defines a

set of classes, interfaces, enumerations, structures and delegates. The following table outlines
the core members of this namespace:

Class Types Description

Directory/ DirectoryInfo These classes support the manipulation of the system


directory structure
DriveInfo This class provides detailed information regarding the drives
that given machine has.
FileStream This gets you random file access with data represented as a
stream of bytes
File/FileInfo These set of classes manipulate a computer’s files
Path It performs operations on System.String types that contain
file or directory path information in a platform-neutral
manner
BinaryReader/ BinaryWriter These classes allow you to store and retrieve primitive data
types as binary values
StreamReader/ Used to store textual information to a file
StreamWriter
StringReader/ Stringwriter These classes also work with textual information. However,
the underlying storage is a string buffer rather than a physical
file
BufferedStream This class provides temp storage for a stream of bytes that
you can commit to storage at a later time.

National Institute of Business Management


7
The System.IO provides a class DriveInfo to manipulate the system drive related tasks. The
DriveInfo class provides numerous details such as the total number of drives, calculation of
total hard disk space, available space, drive name, ready status, types and etc. Consider the
following program that shows the total disk drives:

1. DriveInfo[] di = DriveInfo.GetDrives();
2. Console.WriteLine("Total Partitions");
3.
4. foreach(DriveInfo items in di)
5. {
6. Console.WriteLine(items.Name);
7. }

The following code snippets perform the rest of the DriveInfo class method operations in
details. It displays specific drive full information.

1. using System;
2. using System.IO;
3.
4. namespace DiskPartition
5. {
6. class Program
7. {
8. static void Main(string[] args)
9. {
10. DriveInfo[] di = DriveInfo.GetDrives();
11.
12. Console.WriteLine("Total Partitions");
13. Console.WriteLine("---------------------");
14. foreach(DriveInfo items in di)
15. {
16. Console.WriteLine(items.Name);
17. }
18. Console.Write("\nEnter the Partition::");
19. string ch = Console.ReadLine();
20.
21. DriveInfo dInfo = new DriveInfo(ch);
22.
23. Console.WriteLine("\n");
24.
25. Console.WriteLine("Drive Name::{0}",dInfo.Name);
26. Console.WriteLine("Total Space::{0}", dInfo.TotalSize);
27. Console.WriteLine("Free Space::{0}", dInfo.TotalFreeSpace);
28. Console.WriteLine("Drive Format::{0}", dInfo.DriveFormat);
29. Console.WriteLine("Volume Label::{0}", dInfo.VolumeLabel);
30. Console.WriteLine("Drive Type::{0}", dInfo.DriveType);
31. Console.WriteLine("Root dir::{0}", dInfo.RootDirectory);
32. Console.WriteLine("Ready::{0}", dInfo.IsReady);
33.
34. Console.ReadKey();
35. }
36. }
37. }

National Institute of Business Management


8
3. Exception Handling

An exception is an erroneous situation that occurs during program execution. Exceptional


situation arises when an operation cannot be completed normally. When an exception occurs
in an application, the system throws an error. The error is handled through the process of
exceptionhandling.

C# provides built-in support for handling anomalous situations, known as exceptions, which
may occur during the execution of your program. These exceptions are handled by code that is
outside the normal flow of control.

Exception handling is a way to handle errors at runtime that cause application termination.

 Exception is a violation of an Interface’s implicit assumptions.

 Run time errors due to incorrect inputs.

 Exceptional situation occurs when the program is run and user doing a mistake like
input incorrect data type

Benefits of Exception Handling

 Assures that code will run without run time errors.

 Consolidates handling of potential failures without stopping your code with errors.

 Helps to fix the bugs in code.

National Institute of Business Management


9
3.1. The try block

A try block should have at least one catch or finally block. We can use both catch and finally
block after the try block.
Remember there should be no other code between these blocks.
In the above code if no errors or errors are found, the flow of execution goes to the third block
finally. If an exception is thrown execution goes to a catch block.

3.2. Exception Nesting

You can create an exception inside of another. This is referred to as nesting an exception.
To nest an exception, write a try block in the body of the parent exception. The nested try block
must be followed by its own catches clause.

3.3. The catch block

In this block you implement methods for dealing with any possible errors of the try block. At
the end of this block execution continues to the last code block.
When an exception occurs in the try section, code compilation is transferred to the catch block.

using System;

namespace exception_example1

class Program

static void Main(string[] args)

try

int i, k = 0, j;

Console.Write("Enter a number one: ");

i = Convert.ToInt32(Console.ReadLine());

Console.Write("Enter a number two: ");

j = Convert.ToInt32(Console.ReadLine());

National Institute of Business Management


10
k = i / j;

Console.WriteLine("Output of division : {0}", k);

Console.ReadKey();

catch (DivideByZeroException ex)

Console.WriteLine(ex.Message);

Console.ReadKey();

In the above program if you input the second number as zero (0) it will generate
DivideByZeroException.

The catch statement of the catch block takes an object of the exception class as a parameter,
which refers to the raised exception. When the exception is caught, the statements within the
catch blocks are executed.

One of the properties of the Exception class is called Message. This property contains a string
that describes the type of error that occurred. You can then access this Exception. Message
property to display an error message if you want.

National Institute of Business Management


11
using System;

namespace exceptionHandling_example3

class Program

static void Main(string[] args)

double Operand1, Operand2;

double Result = 0.00;

char Operator;

Console.WriteLine("This program allows you to perform an operation on two numbers");

try

Console.Write("Enter a number: ");

Operand1 = double.Parse(Console.ReadLine());

Console.Write("Enter an operator: ");

Operator = char.Parse(Console.ReadLine());

Console.Write("Enter a number: ");

Operand2 = double.Parse(Console.ReadLine());

if (Operator != '+' &&

Operator != '-' &&

Operator != '*' &&

Operator != '/')

throw new Exception(Operator.ToString());

if (Operator == '/') if (Operand2 == 0)

throw new DivideByZeroException("Division by zero is not allowed");

switch (Operator)

National Institute of Business Management


12
{

case '+':

Result = Operand1 + Operand2;

break;

case '-':

Result = Operand1 - Operand2;

break;

case '*':

Result = Operand1 * Operand2;

break;

case '/':

Result = Operand1 / Operand2;

break;

default:

Console.WriteLine("Bad Operation");

break;

Console.WriteLine("\n{0} {1} {2} = {3}", Operand1, Operator, Operand2, Result);

catch (DivideByZeroException ex)

Console.WriteLine(ex.Message);

catch (Exception ex)

Console.WriteLine("\nOperation Error: {0} is not a valid operator", ex.Message);

Console.ReadKey();

National Institute of Business Management


13
3.4. The finally block

The finally block is executed whether or not an exception was thrown.


The catch block is used to handle exceptions that occur in a try block. The finally block is used
to guarantee the execution of statements, regardless of whether an exception has occurred or
not.

See the code to understand finally block

using System;

namespace exception_example1

class Program

static void Main(string[] args)

int i, k = 0, j;

try

Console.Write("Enter a number one: ");

i = Convert.ToInt32(Console.ReadLine());

Console.Write("Enter a number two: ");

j = Convert.ToInt32(Console.ReadLine());

k = i / j;

catch (DivideByZeroException ex)

Console.WriteLine(ex.Message);

Console.ReadKey();

National Institute of Business Management


14
finally

Console.WriteLine("Output of division : {0}", k);

Console.ReadKey();

Points about finally block

 You can have only one finally block for each try block.
 It is not mandatory to have a finally block after a try block.
 The finally block is used to do all the cleanup code.
 It does not support the error message, but all the code contained in the finally block is
executed after the exception is raised.

To cover unmanaged resource, we use finally block. For example when we are not able to find
file/database exception we close the file.

It is used for cleaning up resources that your program might have used and generic code that
should always be executed.

National Institute of Business Management


15
3.5. Exceptions and Custom Messages

Sometimes, the message provided by the Exception class may not be clear to the normal
users. As an alternative, you can create your own message and display it to the user.

You can display the exception message along with the user defined custom message. See the
program below.

using System;

namespace exceptionHandeling_Example2

class Program

static void Main(string[] args)

int num1, num2, sum;

try

Console.Write("Enter first number : ");

num1 = int.Parse(Console.ReadLine());

Console.Write("Enter second number : ");

num2 = int.Parse(Console.ReadLine());

sum = num1 + num2;

Console.WriteLine(sum);

catch (Exception e)

Console.WriteLine(e.Message);

Console.WriteLine("The error indicates that the input was not provided" +

"in the desired format, You might have provide input not as integer");

Console.ReadKey();

National Institute of Business Management


16
Throwing an Exception

Exceptions can be explicitly generated by a program using the throw keyword.

Exceptions are used to indicate that an error has occurred while running the program.
Exception objects that describe an error are created and then thrown with the throw keyword.
The runtime then searches for the most compatible exception handler.

using System;

namespace exceptionHandling_example4

class Program

static void Main(string[] args)

int total = 0;

int[] arr = new int[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

try

for (int i = 0; i <= 10; i++)

total += arr[i];

throw new System.Exception();

catch(Exception ex)

Console.WriteLine("Unknown error");

Console.ReadLine();

National Institute of Business Management


17
3.6. The Exception Class

To support exception handling, the .NET Framework provides a special class called
Exception. Once the compiler encounters an error, the Exception class allows you to identify
the type of error and take an appropriate action.

Normally, Exception mostly serves as the general class of exceptions. Anticipating various
types of problems that can occur in a program, Microsoft derived various classes from
Exception to make this issue friendlier.

As a result, almost any type of exception you may encounter already has a class created to
deal with it. Therefore, when your program faces an exception, you can easily identify the
type of error.

3.7. The Hierarchy of Exception Class

System.Exception

System.ApplicationException

System.SystemException

SystemException: These exceptions are defined and the common language runtime throws
SystemException. The System.System.Exception acts as a base class for all predefined
exception.

ApplicationException: These exceptions are not defined. The ApplicationException is


thrown by a user program rather than the runtime. They are non-fatal error. If any user-
defined application requires its own exception, it should inherit the exception from the
System.ApplicationException class.

National Institute of Business Management


18
Following are some common exception classes.

Exception Class Cause

SystemException A failed run-time checks; used as a base class


for other.

AccessException Failure to access a type member, such as a


method or field.

ArgumentException An argument to a method was invalid.

ArgumentNullException A null argument was passed to a method that


doesn't accept it.

ArgumentOutOfRangeException Argument value is out of range.

ArithmeticException Arithmetic over - or underflow has occurred.

ArrayTypeMismatchException Attempt to store the wrong type of object in an


array.

BadImageFormatException Image is in the wrong format.

CoreException Base class for exceptions thrown by the


runtime.

DivideByZeroException An attempt was made to divide by zero.

FormatException The format of an argument is wrong.

IndexOutOfRangeException An array index is out of bounds.

InvalidCastExpression An attempt was made to cast to an invalid class.

InvalidOperationException A method was called at an invalid time.

MissingMemberException An invalid version of a DLL was accessed.

NotFiniteNumberException A number is not valid.

NotSupportedException Indicates that a class does not implement a


method.

NullReferenceException Attempt to use an unassigned reference.

OutOfMemoryException Not enough memory to continue execution.

National Institute of Business Management


19
4. Delegates
A delegate in C# is similar to a function pointer in C or C++. Using a delegate allows the
programmer to encapsulate a reference to a method inside a delegate object.
The delegate object can then be passed to code which can call the referenced method, without
having to know at compile time which method will be invoked.

Uses of Delegates

Delegates are useful to offer to the user to customize their behavior.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Delegates
{
public delegate int my_delegate(int a,int b);
class Program
{
static void Main(string[] args)
{
my_delegate del = new my_delegate(abc.ss);
abc obj = new abc();
my_delegate del1 = new my_delegate(obj.ss1);
int a = del(4, 2);
int b = del1(4, 2);
Console.WriteLine("the result of ss is {0} and the result of ss1 is {1}", a, b);
}
}
class abc

National Institute of Business Management


20
{
public static int ss(int i, int j)
{
return i * j;
}
public int ss1(int x, int y)
{
return x + y;
}
}
}

National Institute of Business Management


21
References

Source : http://www.dotnet-tricks.com/Tutorial/csharp/QD39230314-Understanding-
Delegates-in-C#.html
Source : http://www.dotnet-tricks.com/Tutorial/csharp/EJFQ291113-A-Deep-Dive-into-C#-
Errors-orExceptions-Handling.html
Source : http://www.ssw.uni-linz.ac.at/Teaching/Lectures/CSharp/Tutorial
Source : http://www.idc-
online.com/technical_references/information_technology/Understanding_Delegates_in_Csha
rp
Source : http://www.wikipedia.com/cSharp/file-handling-in-c#.html

National Institute of Business Management


22

You might also like