OOP Concepts in C#
OOP Concepts in C#
OOP Concepts 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
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.
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
A class is the core of any modern Object Oriented Programming language such as C#.
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. }
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:
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.
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:
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. }
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.
Exceptional situation occurs when the program is run and user doing a mistake like
input incorrect data type
Consolidates handling of potential failures without stopping your code with errors.
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.
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.
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
try
int i, k = 0, j;
i = Convert.ToInt32(Console.ReadLine());
j = Convert.ToInt32(Console.ReadLine());
Console.ReadKey();
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.
namespace exceptionHandling_example3
class Program
char Operator;
try
Operand1 = double.Parse(Console.ReadLine());
Operator = char.Parse(Console.ReadLine());
Operand2 = double.Parse(Console.ReadLine());
Operator != '/')
switch (Operator)
case '+':
break;
case '-':
break;
case '*':
break;
case '/':
break;
default:
Console.WriteLine("Bad Operation");
break;
Console.WriteLine(ex.Message);
Console.ReadKey();
using System;
namespace exception_example1
class Program
int i, k = 0, j;
try
i = Convert.ToInt32(Console.ReadLine());
j = Convert.ToInt32(Console.ReadLine());
k = i / j;
Console.WriteLine(ex.Message);
Console.ReadKey();
Console.ReadKey();
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.
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
try
num1 = int.Parse(Console.ReadLine());
num2 = int.Parse(Console.ReadLine());
Console.WriteLine(sum);
catch (Exception e)
Console.WriteLine(e.Message);
"in the desired format, You might have provide input not as integer");
Console.ReadKey();
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
int total = 0;
try
total += arr[i];
catch(Exception ex)
Console.WriteLine("Unknown error");
Console.ReadLine();
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.
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.
Uses of Delegates
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
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