Cs2041 Csharp Unit II Notes
Cs2041 Csharp Unit II Notes
SRM University,Kattankulathur,chennai-603203
Information Technology
CS2041 ( C# and .Net Framework) VII-Sem-IT
( Anna University 2008-Regulations)
UNIT-II-Notes
1) Similarities : When similarities are existing between two or more classes, apply inheritance.
2) Extension : When additional features are needed in existing class, use inheritance and code only
additional features in the new class.
3) Relationship : If relationship exist between classes such as IS-A, IS-A-KIND-OF, or IS-LIKE or IS-
A-Type-OF, use inheritance
4) Generalization : Inheritance is advisible when generalization is fixed and does not require any
modification or change.
5) Specialization : The inherited class is a specialized one having more data and functionalities.
Syntax
-------
-------
}
(5) Illustrate with an example inheritance in C#.
\
Example implementing inheritance in C#.NET
using System;
namespace ProgramCall
{
class Base
2
{
int A, B;
}
class Derived : Base
{
int C;
public void Get()
{
//Accessing base class method in derived class
GetAB();
}
}
class MainClass
{
Console.Read();
}
}
}
Output
1. Single Inheritance
2. Hierarchical Inheritance
3. Multi Level Inheritance
4. Hybrid Inheritance
5. Multiple Inheritance
1. Single Inheritance
when a single derived class is created from a single base class then the inheritance is called as single
inheritance.
2. Hierarchical Inheritance
when more than one derived class are created from a single base class, then that inheritance is called
as hierarchical inheritance.
4
when a derived class is created from another derived class, then that inheritance is called as multi
level inheritance.
4. Hybrid Inheritance
Any combination of single, hierarchical and multi level inheritances is called as hybrid inheritance.
5. Multiple Inheritance
when a derived class is created from more than one base class then that inheritance is called as
multiple inheritance. But multiple inheritance is not supported by .net using classes and can be done
using interfaces.
Handling the complexity that causes due to multiple inheritance is very complex. Hence it was not
supported in dotnet with class and it can be done with interfaces.
When a method is declared as abstract in the base class then it is not possible to define it in the
derived class and every derived class of that class must provide its own definition for that method.
5
When a class contains at least one abstract method, then the class must be declared as abstract class.
When a class is declared as abstract class, then it is not possible to create an instance for that class.
But it can be used as a parameter in a method.
Example
The following example creates three classes shape, circle and rectangle where circle and rectangle
are inherited from the class shape and overrides the methods Area() and Circumference() that are
declared as abstract in Shape class and as Shape class contains abstract methods it is declared as
abstract class.
using System;
namespace ProgramCall
{
//Abstract class
abstract class Shape1
{
protected float R, L, B;
L = float.Parse(Console.ReadLine());
B = float.Parse(Console.ReadLine());
}
}
}
class MainClass
{
public static void Calculate(Shape1 S)
{
}
static void Main()
{
Console.WriteLine();
Console.Read();
}
7
}
}
Output
Enter Length : 10
Enter Breadth : 12
Area : 120
Circumference : 44
Enter Radius : 5
Area : 78.5
Circumference : 31.4
Note
In the above example method calculate takes a parameter of type Shape1 from which rectangle1 and circle1
classes are inherited.
A base class type parameter can take derived class object as an argument. Hence the calculate method can
take either rectangle1 or circle1 object as argument and the actual argument in the parameter S will be
determined only at runtime and hence this example is an example for runtime polymorphism
Sealed Classes
When you want to restrict your classes from being inherited by others you can create the class as sealed
class.
To create a class as sealed class, create the class using the keyword sealed.
Sealed Methods
The virtual nature of a method persists for any number of levels of inheritance.
For example there is a class “A” that contains a virtual method “M1”. Another class “B” is inherited from
“A” and another class “C” is inherited from “B”. In this situation class “C” can override the method “M1”
regardless of whether class “B” overrides the method “M1”.
At any level of inheritance, if you want to restrict next level of derived classes from overriding a virtual
method, then create the method using the keyword sealed along with the keyword override.
Polymorphism is often referred to as the third pillar of object-oriented programming, after encapsulation and
inheritance. Polymorphism is a Greek word that means "many-shaped" and it has two distinct aspects:
1. At run time, objects of a derived class may be treated as objects of a base class in places such as
method parameters and collections or arrays. When this occurs, the object's declared type is no
longer identical to its run-time type.
2. Base classes may define and implement virtual methods, and derived classes can override them,
which means they provide their own definition and implementation. At run-time, when client code
calls the method, the CLR looks up the run-time type of the object, and invokes that override of the
virtual method. Thus in your source code you can call a method on a base class, and cause a derived
class's version of the method to be executed.
Virtual methods enable you to work with groups of related objects in a uniform way. For example, suppose
you have a drawing application that enables a user to create various kinds of shapes on a drawing surface.
You do not know at compile time which specific types of shapes the user will create. However, the
application has to keep track of all the various types of shapes that are created, and it has to update them in
response to user mouse actions. You can use polymorphism to solve this problem in two basic steps:
1. Create a class hierarchy in which each specific shape class derives from a common base class.
2. Use a virtual method to invoke the appropriate method on any derived class through a single call to
the base class method.
First, create a base class called Shape, and derived classes such as Rectangle, Circle, and Triangle. Give the
Shape class a virtual method called Draw, and override it in each derived class to draw the particular shape
that the class represents. Create a List<Shape> object and add a Circle, Triangle and Rectangle to it. To
update the drawing surface, use a foreach loop to iterate through the list and call the Draw method on each
Shape object in the list. Even though each object in the list has a declared type of Shape, it is the run-time
type (the overridden version of the method in each derived class) that will be invoked.
C#
// Virtual method
public virtual void Draw()
{
9
class Program
{
static void Main(string[] args)
{
// Polymorphism at work #1: a Rectangle, Triangle and Circle
// can all be used whereever a Shape is expected. No cast is
// required because an implicit conversion exists from a derived
// class to its base class.
System.Collections.Generic.List<Shape> shapes = new System.Collections.Generic.List<Shape>();
shapes.Add(new Rectangle());
shapes.Add(new Triangle());
shapes.Add(new Circle());
/* Output:
Drawing a rectangle
Performing base class drawing tasks
Drawing a triangle
Performing base class drawing tasks
Drawing a circle
Performing base class drawing tasks
*/
(10) What are interfaces? Illustrate with an example how interfaces are implemented in C#.
An interface contains only the signatures of methods, properties, events or indexers. A class or struct that
implements the interface must implement the members of the interface that are specified in the interface
definition. In the following example, class ImplementationClass must implement a method named
SampleMethod that has no parameters and returns void.
For more information and examples, see Interfaces (C# Programming Guide).
Example
C#
interface ISampleInterface
{
void SampleMethod();
}
An interface can be a member of a namespace or a class and can contain signatures of the following
members:
Methods
Properties
Indexers
Events
When a base type list contains a base class and interfaces, the base class must come first in the list.
A class that implements an interface can explicitly implement members of that interface. An explicitly
implemented member cannot be accessed through a class instance, but only through an instance of the
interface.
For more details and code examples on explicit interface implementation, see Explicit Interface
Implementation (C# Programming Guide).
The following example demonstrates interface implementation. In this example, the interface contains the
property declaration and the class contains the implementation. Any instance of a class that implements
IPoint has integer properties x and y.
C#
interface IPoint
{
// Property signatures:
int x
{
get;
set;
}
int y
{
get;
set;
}
}
// Constructor:
12
// Property implementation:
public int x
{
get
{
return _x;
}
set
{
_x = value;
}
}
public int y
{
get
{
return _y;
}
set
{
_y = value;
}
}
}
class MainClass
{
static void PrintPoint(IPoint p)
{
Console.WriteLine("x={0}, y={1}", p.x, p.y);
}
Stucture is a composite data type in which the members of different data types are accomodated. It is a value
type. It can be declared and created similar to a class type except the keyword struct is used in the place of
13
using system;
class Student
{
struct Point(int a,int b)
{
x = a;
y = b;
}
Program Output :
14
Example
Sealed classes
Some times,we may like to prevent a class being further subclassed for security reasons. A class that cannot
be subclassed is called Sealed Class.
Example
Any attempt to inherit sealed classes will cause an error and the compiler will not allow it.
15
An interface contains only the signatures of methods, delegates or events. The implementation of the
methods is done in the class that implements the interface. A class that implements an interface can
explicitly implement members of that interface. An explicitly implemented member cannot be accessed
through a class instance, but only through an instance of the interface.
interface ISampleInterface
{
void SampleMethod();
}
class ImplementationClass : ISampleInterface
{
// Explicit interface member implementation:
void ISampleInterface.SampleMethod()
{
// Method implementation.
Console.WriteLine(“ The Implementation class implements the SampleMethod
specified in Interface IsampleInterface”);
}
static void Main()
{
// Declare an interface instance.
ISampleInterface obj = new ImplementationClass();
// Call the member.
obj.SampleMethod();
}
}
...............................
C# provides a mechanism known as properties that has the same capabilities as accesor methods,but it is
much more elegant and simple to use. Using a property,a programmer can get access to data members as
though they are public fields. Properties are some times refered to as “smart fields” as they add smartness
to data fields.
Indexers
Indexers are location indicators and are used to access class objects,just like accessing elements in an array.
An indexer allows accessing individual fields contained in the object of a class using subscript operator [] of
an array.
Indexers are sometimes refered to as 'smart arrays';
An indexer takes an index argument and looks like an array.
The indexer is declared using the keyword this.
The indexer is implemented through get and set accessors for the [] operator.
IMPLEMENTATION OF AN INDEXER
using system;
using System.Collections;
class List
{
Arraylist array = new ArrayList();
public object this[int index]
{
get
{
If (index <0 || index >= array.Count)
{
return null;
}
else
{
return (array[index] = value;
}
}
}
class IndexTest
{
public static void Main()
{
List list = new List();
list[0] = “123”;
list[1] = “abc”;
list[2] = “xyz”;
EVENT
17
An event is a delegate type class member that is used by the object or class to provide a notification to
other objects that an event has occurred. The client object can act on an event by adding an event handler to
the event.
Events are declared using the simple event declaration format as follows :
Examples
Public event EventHandler Click;
Public event RateChange Rate;
EventHandler and RateChange are delegates and Click and Rate are events;
Using system;
//delegate declaration first
Class EventClass
{
//declaration of event
Public event Edelegate status;
Class EventTest
{
Public static void Main()
{
EventClass ec = new EventClass();
EventTest et = new EventTest();
Ec.Status += new EDelegate(et.Eventcatch);
Ec.TriggerEvent();
(16) What are delegates? Explain the syntax for delegate declaration.
A Delegate in C# is a class type object and is used to invoke a method that has been encapsulated into it at
18
Four steps
1) Delegate declaration
2) Delegate methods definition
3) Delegate instantiation
4) Delegate invocation
A Delegate declaration defines a class using the class System.Delegate as a base class.
Delegate methods are functions(defined in a class) whose signature matches the delegate signature exactly.
The delegate instance holds the reference to delegate methods. The instance is used to invoke the methods
indirectly.
DELEGATE DECLARATION
DELEGATE METHODS
The methods whose references are encapsulated into a delegate instance are known as delegate methods or
callable entities. The signature and return type of delegate methods must exactly match the signature and
return type of the delegate.
DELEGATE INSTANTIATION
The syntax for delegate instantiation is given below :
new delegate-type(expression);
DELEGATE INVOCATION
The syntax for delegate invocation :
delegate-object(parameter-list);
//delegate declaration
class MathOperation
return (a + b);
19
return (a - b);
class DelegateTest
//delegate instances
//Invoking Delegates
Int result1 = operation1(200,100);
Int result2 = operation2(200,100);
}
}
……
Program Output
Result1 = 300
Result2 = 100
Publisher
A class containing visual components generating events in a Server Class, or server code is known as
publisher.
The subscribing classes implement the methods to handle the appropriate event.
The method that handles an event is known as an event handler.
This type of notifying and handling events is known as publish/subscribe Design Pattern
When an event is raised, the implementing methods(event handlers) in the subscribing classes are invoked
through the delegate to handle the events.
The publish/subscribe design pattern is implemented by combining delegates and events.
Operator overloading is one of the exciting features of OOP. C# supports the idea of operator overloading.
C# operators can be defined to work with the user defined data types such as structs and classes in much the
same way as the built-in types. Operator overloading provides syntactic convenience by which c# operators
can work with user defined data types.
OVERLOADABLE OPERATORS
Category Operators
Binary Arithmetic +,*,/,-,%
Unary arithmetic +,-,++,--
Binary bitwise &,\,^,<<,>>
Unary bitwise !,~,true,false
Logical operators ==,!=,>=,<=,<,>
Conditional operators &&,||
Compound assignment +=,-+,*=,/=,%=
Other operators [],(),=,?:,new,sizeof,typeof,is,as
Example
Mathematical or physical modelling where we use classes to represents objects such as
coordinates,vectors,matrices,tensors,comples numbers and so on.
To define an additional task to to an operator,we must specify what it means in relation to the class to which
the operator is applied. This is done with the help of a special method called operator method,which
describes the task.
The general form of Operator method is :
EXAMPLE
21
Using System;
Class Overloading
{
Public static void Main()
{
Console.WriteLine(Volume(10));
Console.WriteLine(Volume(2.5F,8));
Console.WriteLine(Volume(100L,75,15);
}
Static int Volume(int x) // Cube
{
return (x * x * x);
}
Return ( l * b * h);
}
}
…………
Program Output
(20) Write a program to declare a base class Printer. Derive classes from Printer to display details
of different types of printers.
Using System;
22
Class Printer;
{
Public virtual void type()
{
Console.WriteLine(“Printer Class”);
}
Class InkJet : Printer
{
Public override void type()
{
Console.WriteLine(“Color Inkjet Printer”);
}
Class PrinterTest
{
Public static void Main()
{
Printer p = new printer();
ElectroMechPrinter e = new ElectroMechPrinter();
InkJet I = new InkJet();
DMP d = new DMP();
Printer p1 = I;
p.type();
e.type();
i.type();
d.type();
p1,type();
}
}
……………………
Program Output
Printer Class
23
(21) Write a program by having an abstract class Solid and implement Cylinder,Cone and Sphere
by inheriting from Solid to find surface area and volume.
Using system;
Public delegate void ButtonDelegate(); // Delegate declaration
Public interface ButtonInterface
{
Event ButtonDelegate ButtonEvent;
Void OpenFile();
}
Public class ServerClass : ButtonInterface
{
Public event ButtonDelegate ButtonEvent; //Event declaration
Public void OpenFile() //method that calls the event
{
If (ButtonEvent != null )
ButtonEvent(); //Raising the event
}
}
Public class clientclass
{
Public clientclass
{
ButtonInterface Server = new ServerClass();
………………………..
Program Output
A file is opened by clicking the button
25
// Constructor.
public Complex(int real, int imaginary)
{
this.real = real;
this.imaginary = imaginary;
}
class TestComplex
{
static void Main()
{
Complex num1 = new Complex(2, 3);
Complex num2 = new Complex(3, 4);
/* Output:
First complex number: 2 + 3i
Second complex number: 3 + 4i
The sum of the two numbers: 5 + 7i
*/