Вы находитесь на странице: 1из 23

UNIT-2-OBJECT ORIENTED ASPECTSOF C#

OOPS Concepts, Features & Fundamentals


OOPS contains list of elements that are very helpful to make object oriented
programming stronger. Here is the list of top 10 OOPS concepts that we can implement
in all major programming languages like c#, vb.net etc.

1] Class:

A class is a collection of objects and represents description of objects that share same
attributes and actions. It contains characteristics of the objects such as objects
attributes, actions or behaviors.

Here is the syntax and declaration example of Class:

public class Bike


{
//your code goes here..
}
2] Method:
Method is an object’s behavior.

For example, if you consider “Bike” as a class then its behavior is to get bike color,
engine, mileage etc. Here is the example of Method:

public class Bike


{
//here is some properties of class Bike
public string color;
public string engine;
public int mileage;
//here is some behavior/methods of class Bike
public string GetColor()
{
return "red";
}
public int GetMileage()
{
return 65;
}
}
In above example GetColor() and GetMileage() are the methods considered as a object’s
behavior.
3] Object:
An object is a real-world entity that keeps together property states and behaviors.

For example, A “Bike” usually has common elements such as bike color, engine, mileage
etc. In OOP terminology these would be called as a Class Properties or Attributes of a
Bike object. Here is the example of Object:

public class Bike


{
//This is the class that contains all properties and behavior of an object
//here is some properties of class Bike
public string color;

15SE329E-Visual Programming Notes-Unit-II


public string engine;
public int mileage;
//here is some behavior of class Bike
public string GetColor()
{
return "red";
}
public int GetMileage()
{
return 65;
}
}
Now we have a complete set of class with its properties and methods. So the question
raise in mind is how we can access the class with its object? Right?

It is simple to create its object and access Bike class. You can create object of class via
single line of code as shown below.

//It also considered as an "Instance of a Bike Class"


Bike objBike = new Bike();
//Accessing Bike class methods
objBike.GetColor();
objBike.GetMileage();

Constructors in C#:
Constructor:
Constructor is a special method of a class which will invoke automatically whenever
instance or object of class is created. Constructors are responsible for object initialization
and memory allocation of its class. If we create any class without constructor, the
compiler will automatically create one default constructor for that class. There is always
at least one constructor in every class.
Here you need to remember that a class can have any number of constructors and
constructors don’t have any return type, not even void and within a class we can create
only one static constructor.
Generally constructor name should be same as class name. If we want to create
constructor in a class we need to create a constructor method name same as class name
check below sample method for constructor
Example:
class SampleA
{
public SampleA(){
Console.WriteLine("Sample A Test Method"); }}
Types of Constructor
Basically constructors are 5 types those are
1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor
4. Static Constructor
5. Private Constructor
1.Default Constructor

15SE329E-Visual Programming Notes-Unit-II


A constructor without having any parameters called default constructor. In this
constructor every instance of the class will be initialized without any parameter values
like as shown below
using System;
namespace ConsoleApplication3
{
class Sample
{
public string param1, param2;
public Sample() // Default Constructor
{
param1 = "Welcome";
param2 = "Aspdotnet-Suresh";
}
}
class Program
{
static void Main(string[] args)
{
Sample obj=new Sample(); // Once object of class created automatically constructor
will be called
Console.WriteLine(obj.param1);
Console.WriteLine(obj.param2);
Console.ReadLine();
}}}
When we run above program it will show output like as shown below
Output
Welcome
Aspdotnet-Suresh
2.Parameterized Constructors
A constructor with at least one parameter is called as parameterized constructor. In
parameterized constructor we can initialize each instance of the class to different values
like as shown below
using System;
namespace ConsoleApplication3{
class Sample{
public string param1, param2;
public Sample(string x, string y) // Declaring Parameterized constructor with
Parameters
{
param1 = x;
param2 = y;
}
}

15SE329E-Visual Programming Notes-Unit-II


class Program
{
static void Main(string[] args)
{
Sample obj=new Sample("Welcome","Aspdotnet-Suresh"); // Parameterized
Constructor Called
Console.WriteLine(obj.param1 +" to "+ obj.param2);
Console.ReadLine();
}}}
When we run above program it will show output like as shown below
Output
Welcome to Aspdotnet-Suresh
3.Copy Constructor
A parameterized constructor that contains a parameter of same class type is called as
copy constructor. Main purpose of copy constructor is to initialize new instance to the
values of an existing instance. Check below example for this
using System;
namespace ConsoleApplication3
{
class Sample
{
public string param1, param2;
public Sample(string x, string y)
{
param1 = x;
param2 = y;}
public Sample(Sample obj) // Copy Constructor
{
param1 = obj.param1;
param2 = obj.param2;}}
class Program
{
static void Main(string[] args)
{
Sample obj = new Sample("Welcome", "Aspdotnet-Suresh"); // Create instance to class
Sample
Sample obj1=new Sample(obj); // Here obj details will copied to obj1
Console.WriteLine(obj1.param1 +" to " + obj1.param2);
Console.ReadLine();
}}}
When we run above program it will show output like as shown below
Output
Welcome to Aspdotnet-Suresh

15SE329E-Visual Programming Notes-Unit-II


4.Static Constructor
When we declared constructor as static it will be invoked only once for any number of
instances of the class and it’s during the creation of first instance of the class or the first
reference to a static member in the class. Static constructor is used to initialize static
fields of the class and to write the code that needs to be executed only once.
using System;
namespace ConsoleApplication3
{
class Sample
{
public string param1, param2;
static Sample()
{
Console.WriteLine("Static Constructor");
}
public Sample()
{
param1 = "Sample";
param2 = "Instance Constructor";
}}
class Program
{
static void Main(string[] args)
{
// Here Both Static and instance constructors are invoked for first instance
Sample obj=new Sample();
Console.WriteLine(obj.param1 + " " + obj.param2);
// Here only instance constructor will be invoked
Sample obj1 = new Sample();
Console.WriteLine(obj1.param1 +" " + obj1.param2);
Console.ReadLine();
}}}
When we run above program we will get output like as shown below
Output
Static Constructor
Sample Instance Constructor
Sample Instance Constructor
Importance points of static constructor
- Static constructor will not accept any parameters because it is automatically called
by CLR.
- Static constructor will not have any access modifiers.
- Static constructor will execute automatically whenever we create first instance of
class
- Only one static constructor will allowed.
15SE329E-Visual Programming Notes-Unit-II
5.Private Constructor
Private constructor is a special instance constructor used in a class that contains static
member only. If a class has one or more private constructor and no public constructor
then other classes is not allowed to create instance of this class this mean we can
neither create the object of the class nor it can be inherit by other class. The main
purpose of creating private constructor is used to restrict the class from being
instantiated when it contains every member as static.
using System;
namespace ConsoleApplication3
{
public class Sample
{
public string param1, param2;
public Sample(string a,string b)
{
param1 = a;
param2 = b;
}
private Sample() // Private Constructor Declaration
{
Console.WriteLine("Private Constructor with no prameters");}}
class Program
{
static void Main(string[] args)
{
// Here we don't have chance to create instace for private constructor
Sample obj = new Sample("Welcome","to Aspdotnet-Suresh");
Console.WriteLine(obj.param1 +" " + obj.param2);
Console.ReadLine();
}}}
Output
Welcome to Aspdotnet-Suresh

In above method we can create object of class with parameters will work fine. If create
object of class without parameters it will not allow us create.
// it will works fine
Sample obj = new Sample("Welcome","to Aspdotnet-Suresh");
// it will not work because of inaccessability
Sample obj=new Sample();
Important points of private constructor
- One use of private construct is when we have only static member.
- Once we provide a constructor that is either private or public or any, the compiler
will not allow us to add public constructor without parameters to the class.

15SE329E-Visual Programming Notes-Unit-II


- If we want to create object of class even if we have private constructors then we
need to have public constructor along with private constructor
INDEXERS AND PROPERTIES
An indexer allows an object to be indexed such as an array. When you define an indexer
for a class, this class behaves similar to a virtual array. You can then access the instance
of this class using the array access operator ([ ]).
Syntax
A one dimensional indexer has the following syntax:
element-type this[int index]
{
// The get accessor.
get
{
// return the value specified by index
}
// The set accessor.
set
{
// set the value specified by index}}
Use of Indexers
Declaration of behavior of an indexer is to some extent similar to a property. similar to
the properties, you use get and set accessors for defining an indexer. However,
properties return or set a specific data member, whereas indexers returns or sets a
particular value from the object instance. In other words, it breaks the instance data into
smaller parts and indexes each part, gets or sets each part.
Defining a property involves providing a property name. Indexers are not defined with
names, but with the this keyword, which refers to the object instance. The following
example demonstrates the concept:
Program:
using System;
namespace IndexerApplication
{
class IndexedNames
{
private string[] namelist = new string[size];
static public int size = 10;
public IndexedNames()
{
for (int i = 0; i < size; i++)
namelist[i] = "N. A.";
} public string this[int index]
{
get
{
string tmp;

15SE329E-Visual Programming Notes-Unit-II


if( index >= 0 && index <= size-1 )
{
tmp = namelist[index];
}
else
{
tmp = "";
}

return ( tmp );
}
set
{
if( index >= 0 && index <= size-1 )
{
namelist[index] = value;
} }}
static void Main(string[] args)
{
IndexedNames names = new IndexedNames();
names[0] = "Zara";
names[1] = "Riz";
names[2] = "Nuha";
names[3] = "Asif";
names[4] = "Davinder";
names[5] = "Sunil";
names[6] = "Rubic";
for ( int i = 0; i < IndexedNames.size; i++ )
{
Console.WriteLine(names[i]);
}
Console.ReadKey();
}}}
Output:
When the above code is compiled and executed, it produces the following result:
Zara
Riz
Nuha
Asif
Davinder
Sunil
Rubic

15SE329E-Visual Programming Notes-Unit-II


N. A.
N. A.
N. A.

Overloaded Indexers

Indexers can be overloaded. Indexers can also be declared with multiple parameters
and each parameter may be a different type. It is not necessary that the indexes have
to be integers. C# allows indexes to be of other types, for example, a string.

The following example demonstrates overloaded indexers:

Program:
using System;
namespace IndexerApplication
{
class IndexedNames
{
private string[] namelist = new string[size];
static public int size = 10;
public IndexedNames()
{
for (int i = 0; i < size; i++)
{
namelist[i] = "N. A.";
}}
public string this[int index]
{
get
{
string tmp;

if( index >= 0 && index <= size-1 )


{
tmp = namelist[index];
}
else
{
tmp = ""; }
return ( tmp );
}
set
{
if( index >= 0 && index <= size-1 )

15SE329E-Visual Programming Notes-Unit-II


{
namelist[index] = value;
}}}
public int this[string name]
{
get
{
int index = 0;
while(index < size)
{
if (namelist[index] == name)
{
return index;
}
index++;
}
return index;}}
static void Main(string[] args)
{
IndexedNames names = new IndexedNames();
names[0] = "Zara";
names[1] = "Riz";
names[2] = "Nuha";
names[3] = "Asif";
names[4] = "Davinder";
names[5] = "Sunil";
names[6] = "Rubic";
//using the first indexer with int parameter
for (int i = 0; i < IndexedNames.size; i++)
{
Console.WriteLine(names[i]);
}
//using the second indexer with the string parameter
Console.WriteLine(names["Nuha"]);
Console.ReadKey();
}}}
Output:
Zara
Riz
Nuha
Asif
Davinder

15SE329E-Visual Programming Notes-Unit-II


Sunil
Rubic
N. A.
N. A.
N. A.
2
Properties:
Properties are named members of classes, structures, and interfaces. Member variables
or methods in a class or structures are called Fields. Properties are an extension of fields
and are accessed using the same syntax. They use accessors through which the values
of the private fields can be read, written or manipulated.
Properties do not name the storage locations. Instead, they have accessors that read,
write, or compute their values.
For example, let us have a class named Student, with private fields for age, name, and
code. We cannot directly access these fields from outside the class scope, but we can
have properties for accessing these private fields.

Accessors:

The accessor of a property contains the executable statements that helps in getting (reading or
computing) or setting (writing) the property. The accessor declarations can contain a get accessor, a set
accessor, or both. For example:
// Declare a Code property of type string:
public string Code
{
get
{
return code;
}
set
{
code = value;
}}
// Declare a Name property of type string:
public string Name
{
get
{
return name;
}
set
{
name = value;
}}
// Declare a Age property of type int:

15SE329E-Visual Programming Notes-Unit-II


public int Age
{
get
{
return age;
}
set
{
age = value;
}}
Example
The following example demonstrates use of properties:
using System;
namespace tutorialspoint
{
class Student
{
private string code = "N.A";
private string name = "not known";
private int age = 0;
// Declare a Code property of type string:
public string Code
{
get
{
return code;
}
set
{
code = value;}}
// Declare a Name property of type string:
public string Name
{
get
{
return name;
}
set
{
name = value; }}
// Declare a Age property of type int:
public int Age

15SE329E-Visual Programming Notes-Unit-II


{
get
{
return age;}
set
{
age = value;}}
public override string ToString()
{
return "Code = " + Code +", Name = " + Name + ", Age = " + Age;
}}
class ExampleDemo
{
public static void Main()
{
// Create a new Student object:
Student s = new Student()
// Setting code, name and the age of the student
s.Code = "001";
s.Name = "Zara";
s.Age = 9;
Console.WriteLine("Student Info: {0}", s);
//let us increase age
s.Age += 1;
Console.WriteLine("Student Info: {0}", s);
Console.ReadKey();
}}}
When the above code is compiled and executed, it produces the following result:
Student Info: Code = 001, Name = Zara, Age = 9
Student Info: Code = 001, Name = Zara, Age = 10
Abstract Properties
An abstract class may have an abstract property, which should be implemented in the
derived class. The following program illustrates this:
using System;
namespace tutorialspoint{
public abstract class Person{
public abstract string Name{
get;
set;}
public abstract int Age
{
get;

15SE329E-Visual Programming Notes-Unit-II


set;
}}
class Student : Person
{
private string code = "N.A";
private string name = "N.A";
private int age = 0;
// Declare a Code property of type string:
public string Code
{
get
{
return code;
}
set
{
code = value;
}}
// Declare a Name property of type string:
public override string Name
{
get
{
return name;
}
set
{
name = value;} }
// Declare a Age property of type int:
public override int Age
{
get
{
return age;
}
set
{
age = value;}}
public override string ToString()
{
return "Code = " + Code +", Name = " + Name + ", Age = " + Age;}}
class ExampleDemo

15SE329E-Visual Programming Notes-Unit-II


{
public static void Main()
{
// Create a new Student object:
Student s = new Student();
// Setting code, name and the age of the student
s.Code = "001";
s.Name = "Zara";
s.Age = 9;
Console.WriteLine("Student Info:- {0}", s);
//let us increase age
s.Age += 1;
Console.WriteLine("Student Info:- {0}", s);
Console.ReadKey();
}}}
Output:
Student Info: Code = 001, Name = Zara, Age = 9
Student Info: Code = 001, Name = Zara, Age = 10
Interfaces in C#:
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.

Declaring Interfaces

Interfaces are declared using the interface keyword. It is similar to class declaration.
Interface statements are public by default. Following is an example of an interface
declaration:

public interface ITransactions


{
// interface members
void showTransaction();
double getAmount();
}
Example

The following example demonstrates implementation of the above interface:

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System;
namespace InterfaceApplication
{

15SE329E-Visual Programming Notes-Unit-II


public interface ITransactions
{
// interface members
void showTransaction();
double getAmount();
}
public class Transaction : ITransactions
{
private string tCode;
private string date;
private double amount;
public Transaction()
{
tCode = " ";
date = " ";
amount = 0.0;
}
public Transaction(string c, string d, double a)
{
tCode = c;
date = d;
amount = a;
}
public double getAmount()
{
return amount;
}
public void showTransaction()
{
Console.WriteLine("Transaction: {0}", tCode);
Console.WriteLine("Date: {0}", date);
Console.WriteLine("Amount: {0}", getAmount());
}}
class Tester
{
static void Main(string[] args)
{
Transaction t1 = new Transaction("001", "8/10/2012", 78900.00);
Transaction t2 = new Transaction("002", "9/10/2012", 451900.00);
t1.showTransaction();
t2.showTransaction();
Console.ReadKey();}}}

15SE329E-Visual Programming Notes-Unit-II


When the above code is compiled and executed, it produces the following result:
Transaction: 001
Date: 8/10/2012
Amount: 78900
Transaction: 002
Date: 9/10/2012
Amount: 451900

Interfaces have the following properties −

• An interface is implicitly abstract. You do not need to use the abstractkeyword


while declaring an interface.

• Each method in an interface is also implicitly abstract, so the abstract keyword is


not needed.

• Methods in an interface are implicitly public.

Abstract Class:

We cannot create an object of an abstract class and can call the method of abstract
class with the help of class name only.

Example:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace ConsoleApplication4

abstract class M1

public int add(int a, int b)

return (a + b); }}

class M2 :M1
15SE329E-Visual Programming Notes-Unit-II
{

public int mul(int a, int b)

return a * b; }}

class test

static void Main(string[] args)

M2 ob = new M2();

int result = ob.add(10, 20);

Console.WriteLine("the result is {0}", result);

Console.ReadLine();

}}}

Output:

The Result is 30

Interface:

The syntax of an Interface looks like this:

interface

{ //Interface member

NOTE :

An Interface member cannot contain code bodies.

Type definition members are forbidden.

Properties are defined in an interface with the help of an access block get and set, which
are permitted for the property.

e.g. Interface myInterface

int myint

15SE329E-Visual Programming Notes-Unit-II


{

get;

set;

}}

Take a look in an interface example:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace ConsoleApplication3

interface MyInterface

void myMethod();

class MyClass : MyInterface

public static void Main()

MyClass cls = new MyClass();

cls.myMethod();}

public void myMethod()

Console.WriteLine("welcome to MCN IT SOLUTION");

Console.ReadLine();

}}}

Output: Welcome to MCN IT Solution

DIFFERENCE BETWEEN AN ABSTRACT CLASS AND AN INTERFACE:

1. An Abstract class doesn't provide full abstraction but an interface does provide
full abstraction; i.e. both a declaration and a definition is given in an abstract
class but not so in an interface.
2. Using Abstract we can not achieve multiple inheritance but using an Interface we
can achieve multiple inheritance.
3. We can not declare a member field in an Interface.

15SE329E-Visual Programming Notes-Unit-II


4. We can not use any access modifier i.e. public , private , protected , internal etc.
because within an interface by default everything is public.
5. An Interface member cannot be defined using the keyword static, virtual, abstract
or sealed.

EXCEPTIONS:
An exception is a problem that arises during the execution of a program. A C# exception
is a response to an exceptional circumstance that arises while a program is running,
such as an attempt to divide by zero.

Exceptions provide a way to transfer control from one part of a program to another. C#
exception handling is built upon four keywords: try, catch, finally, and throw.

• try: A try block identifies a block of code for which particular exceptions is
activated. It is followed by one or more catch blocks.

• catch: A program catches an exception with an exception handler at the place in


a program where you want to handle the problem. The catch keyword indicates
the catching of an exception.

• finally: The finally block is used to execute a given set of statements, whether
an exception is thrown or not thrown. For example, if you open a file, it must be
closed whether an exception is raised or not.

• throw: A program throws an exception when a problem shows up. This is done
using a throw keyword.
Basics of Exception Handling
Up normal conditions or unexpected condition in a program during runtime is called
EXCEPTION. Exceptions are run time anomalies or run time errors or unusual conditions that a
program may encounter while executing.
Exceptions are of two kinds, namely, synchronous exception and asynchronous exceptions
1. Asynchronous exception:

Excepections are caused by events or faults are unrelated to the program and beyond
the control of the program.
Eg: keyboard intrepts, disk failure, hardware malfunction.
2. Exception which occurs during the pgm execution due to some fault in input
data(Technique with in the program).

Eg:overflow(divide by zero), array out of range.


The purpose of the exception handling mechanism is to provide means to detect and report an
“exceptional circumstance”. So that appropriate action can be taken. The mechanism suggests a
separate error handling that performs the following tasks:
1. Find the problem (Hit the Exception)
2. Inform that an error has occurred (Throw the exception)
3. Receive the error information (Catch the exception)
4. Take corrective actions (Handle the Exception).
The error handling code basically consists of two segments, one to detect errors and to throw
exceptions, and the other to catch the exceptions and to take appropriate actions.

15SE329E-Visual Programming Notes-Unit-II


Need for Exceptional Handling:
Exceptional handling mechanism is needed in C++ because of inappropriateness of all the
traditional solutions while working with objects and in distributed environment. The following text
stresses on the needs of exceptional handling.
1. Dividing the Error Handling: The Library Designer and Library User
2. Unconditional Termination and Programmer Preferred Termination
3. Separating Error Reporting and Error Handling
4.The Object Destroy Problem:
DIVIDE BY ZERO EXCEPTION
#include<iostream.h>
void main( )
{
int a,b;
cout<< “ enter values of a and b \n”;
cin>>a;
cin>>b;
int x=a-b;
try {
if(x !=0) {
cout<< “ Result (a/x) = “ a/x << “\n”; }
else {
throw(x);}}
catch(int i) {
cout<< “ Exception caught: x= “<< x <<”\n”; }
cout<< “ The End”;}
output:
First Run
Enter values of a and b
20 15
Result(a/x) = 4
The End Second Run
Enter values of a and b
10 0
Exception caught:
The End
The program detects and catches a division-by- zero problems. The output of first run shows a
successful execution. When no exception is thrown, the catch block is skipped and execution
resumes with the first line after the catch. In the second run, the denominator x becomes zero and
therefore a division-by-zero situation occurs. This execution is thrown using the object x. since the
execution object is an int type, the catch statement containing int type argument catches the the
exception and displays necessary message.

15SE329E-Visual Programming Notes-Unit-II


Creating User-Defined Exceptions

You can also define your own exception. User-defined exception classes are derived
from the Exception class. The following example demonstrates this:

Program:

using System;

namespace UserDefinedException

class TestTemperature

static void Main(string[] args)

Temperature temp = new Temperature();

try

temp.showTemp();

catch(TempIsZeroException e)

Console.WriteLine("TempIsZeroException: {0}", e.Message);

Console.ReadKey();}}}

public class TempIsZeroException: Exception

public TempIsZeroException(string message): base(message) {

}
15SE329E-Visual Programming Notes-Unit-II
}

public class Temperature

int temperature = 0;

public void showTemp()

if(temperature == 0)

throw (new TempIsZeroException("Zero Temperature found"));}

else{

Console.WriteLine("Temperature: {0}", temperature);}}}

When the above code is compiled and executed, it produces the following result:

TempIsZeroException: Zero Temperature found.

15SE329E-Visual Programming Notes-Unit-II

Вам также может понравиться