C#Practical Examples
C#Practical Examples
Encapsulation, in
object oriented programming methodology, prevents access to implementation details.
Abstraction and encapsulation are related features in object oriented programming. Abstraction allows making relevant information
visible and encapsulation enables a programmer to implement the desired level of abstraction.
Encapsulation is implemented by using access specifiers. An access specifier defines the scope and visibility of a class member.
C# supports the following access specifiers:
Public
Private
Protected
Internal
Protected internal
Public access specifier allows a class to expose its member variables and member functions to other functions and objects. Any
public member can be accessed from outside the class.
using System;
namespace RectangleApplication
{
class Rectangle
{
//member variables
public double length;
public double width;
When the above code is compiled and executed, it produces the following result:
Length: 4.5
Width: 3.5
Area: 15.75
In the preceding example, the member variables length and width are declared public, so they can be accessed from the function
Main() using an instance of the Rectangle class, named r.
The member function Display() and GetArea() can also access these variables directly without using any instance of the class.
The member functions Display() is also declared public, so it can also be accessed from Main() using an instance of the Rectangle
class, named r.
Private access specifier allows a class to hide its member variables and member functions from other functions and objects. Only
functions of the same class can access its private members. Even an instance of a class cannot access its private members.
using System;
namespace RectangleApplication
{
class Rectangle
{
//member variables
private double length;
private double width;
When the above code is compiled and executed, it produces the following result:
Enter Length:
4.4
Enter Width:
3.3
Length: 4.4
Width: 3.3
Area: 14.52
In the preceding example, the member variables length and width are declared private, so they cannot be accessed from the
function Main(). The member functions AcceptDetails() and Display() can access these variables. Since the member functions
AcceptDetails() and Display() are declared public, they can be accessed from Main() using an instance of the Rectangle class,
named r.
Protected access specifier allows a child class to access the member variables and member functions of its base class. This way it
helps in implementing inheritance.
Internal access specifier allows a class to expose its member variables and member functions to other functions and objects in the
current assembly. In other words, any member with internal access specifier can be accessed from any class or method defined
within the application in which the member is defined.
using System;
namespace RectangleApplication
{
class Rectangle
{
//member variables
internal double length;
internal double width;
double GetArea()
{
return length * width;
}
public void Display()
{
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}//end class Rectangle
class ExecuteRectangle
{
static void Main(string[] args)
{
Rectangle r = new Rectangle();
r.length = 4.5;
r.width = 3.5;
r.Display();
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result:
Length: 4.5
Width: 3.5
Area: 15.75
In the preceding example, notice that the member function GetArea() is not declared with any access specifier. Then what would be
the default access specifier of a class member if we don't mention any? It is private.
The protected internal access specifier allows a class to hide its member variables and member functions from other class objects
and functions, except a child class within the same application. This is also used while implementing inheritance.
--------------------------------------------------------------------------------------------------------------------
An Interface is defined as a syntactical contract that all the classes inheriting the interface should follow. The interface defines the
'what' part of the syntactical contract and the deriving classes define the 'how' part of the syntactical contract.
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.
Abstract classes to some extent serve the same purpose, however, they are mostly used when only few methods are to be declared
by the base class and the deriving class implements the functionalities.
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:
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace InterfaceApplication
{
}
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();
}
}
}
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
---------------------------------------------------------------------------------------------------------------------------------------------------
One of the most important concepts in object-oriented programming is that of inheritance. Inheritance allows us to define a class in
terms of another class, which makes it easier to create and maintain an application. This also provides an opportunity to reuse the
code functionality and fast implementation time.
When creating a class, instead of writing completely new data members and member functions, the programmer can designate that
the new class should inherit the members of an existing class. This existing class is called the base class, and the new class is
referred to as the derived class.
The idea of inheritance implements the IS-A relationship. For example, mammal IS A animal, dog IS-A mammal hence dog IS-A
animal as well and so on.
A class can be derived from more than one class or interface, which means that it can inherit data and functions from multiple base
class or interface.
using System;
namespace InheritanceApplication
{
class Shape
{
public void setWidth(int w)
{
width = w;
}
public void setHeight(int h)
{
height = h;
}
protected int width;
protected int height;
}
// Derived class
class Rectangle: Shape
{
public int getArea()
{
return (width * height);
}
}
class RectangleTester
{
static void Main(string[] args)
{
Rectangle Rect = new Rectangle();
Rect.setWidth(5);
Rect.setHeight(7);
When the above code is compiled and executed, it produces the following result:
Total area: 35
The derived class inherits the base class member variables and member methods. Therefore the super class object should be
created before the subclass is created. You can give instructions for superclass initialization in the member initialization list.
The following program demonstrates this:
using System;
namespace RectangleApplication
{
class Rectangle
{
//member variables
protected double length;
protected double width;
public Rectangle(double l, double w)
{
length = l;
width = w;
}
public double GetArea()
{
return length * width;
}
public void Display()
{
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}//end class Rectangle
class Tabletop : Rectangle
{
private double cost;
public Tabletop(double l, double w) : base(l, w)
{ }
public double GetCost()
{
double cost;
cost = GetArea() * 70;
return cost;
}
public void Display()
{
base.Display();
Console.WriteLine("Cost: {0}", GetCost());
}
}
class ExecuteRectangle
{
static void Main(string[] args)
{
Tabletop t = new Tabletop(4.5, 7.5);
t.Display();
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result:
Length: 4.5
Width: 7.5
Area: 33.75
Cost: 2362.5
Multiple Inheritance in C#
C# does not support multiple inheritance. However, you can use interfaces to implement multiple inheritance. The following program
demonstrates this:
using System;
namespace InheritanceApplication
{
class Shape
{
public void setWidth(int w)
{
width = w;
}
public void setHeight(int h)
{
height = h;
}
protected int width;
protected int height;
}
}
// Derived class
class Rectangle : Shape, PaintCost
{
public int getArea()
{
return (width * height);
}
public int getCost(int area)
{
return area * 70;
}
}
class RectangleTester
{
static void Main(string[] args)
{
Rectangle Rect = new Rectangle();
int area;
Rect.setWidth(5);
Rect.setHeight(7);
area = Rect.getArea();
// Print the area of the object.
Console.WriteLine("Total area: {0}", Rect.getArea());
Console.WriteLine("Total paint cost: ${0}" , Rect.getCost(area));
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result:
Total area: 35
Total paint cost: $2450
Polymorphism means many forms (ability to take more than one form). In Polymorphism poly means “multiple” and morph means
“forms” so polymorphism means many forms.
In polymorphism we will declare methods with same name and different parameters in same class or methods with same name and
same parameters in different classes. Polymorphism has ability to provide different implementation of methods that are implemented
with same name.
Overloading
Overloading means we will declare methods with same name but different signatures because of this we will perform different tasks
with same method name. This overloading also called as compile time polymorphism or early binding.
Method Overloading or compile time polymorphism means same method names with different signatures (different parameters)
Overriding
Overriding also called as run time polymorphism or late binding or dynamic polymorphism. Method overriding or run time
polymorphism means same method names with same signatures.
In this method overriding or run time polymorphism we can override a method in base class by creating similar function in derived
class this can be achieved by using inheritance principle and using “virtual & override” keywords.
The word polymorphism means having many forms. In object-oriented programming paradigm, polymorphism is often expressed as
'one interface, multiple functions'.
Polymorphism can be static or dynamic. In static polymorphism the response to a function is determined at the compile time. In
dynamic polymorphism , it is decided at run-time.
Static Polymorphism
The mechanism of linking a function with an object during compile time is called early binding. It is also called static binding. C#
provides two techniques to implement static polymorphism. These are:
Function overloading
Operator overloading
Function Overloading
You can have multiple definitions for the same function name in the same scope. The definition of the function must differ from each
other by the types and/or the number of arguments in the argument list. You cannot overload function declarations that differ only by
return type.
Following is the example where same function print() is being used to print different data types:
using System;
namespace PolymorphismApplication
{
class Printdata
{
void print(int i)
{
Console.WriteLine("Printing int: {0}", i );
}
void print(double f)
{
Console.WriteLine("Printing float: {0}" , f);
}
void print(string s)
{
Console.WriteLine("Printing string: {0}", s);
}
static void Main(string[] args)
{
Printdata p = new Printdata();
// Call print to print integer
p.print(5);
// Call print to print float
p.print(500.263);
// Call print to print string
p.print("Hello C++");
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result:
Printing int: 5
Printing float: 500.263
Printing string: Hello C++
Dynamic Polymorphism
C# allows you to create abstract classes that are used to provide partial class implementation of an interface. Implementation is
completed when a derived class inherits from it. Abstract classes contain abstract methods, which are implemented by the derived
class. The derived classes have more specialized functionality.
using System;
namespace PolymorphismApplication
{
abstract class Shape
{
public abstract int area();
}
class Rectangle: Shape
{
private int length;
private int width;
public Rectangle( int a=0, int b=0)
{
length = a;
width = b;
}
public override int area ()
{
Console.WriteLine("Rectangle class area :");
return (width * length);
}
}
class RectangleTester
{
static void Main(string[] args)
{
Rectangle r = new Rectangle(10, 7);
double a = r.area();
Console.WriteLine("Area: {0}",a);
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result:
When you have a function defined in a class that you want to be implemented in an inherited class(es), you use virtual functions.
The virtual functions could be implemented differently in different inherited class and the call to these functions will be decided at
runtime.
using System;
namespace PolymorphismApplication
{
class Shape
{
protected int width, height;
public Shape( int a=0, int b=0)
{
width = a;
height = b;
}
public virtual int area()
{
Console.WriteLine("Parent class area :");
return 0;
}
}
class Rectangle: Shape
{
public Rectangle( int a=0, int b=0): base(a, b)
{
}
public override int area ()
{
Console.WriteLine("Rectangle class area :");
return (width * height);
}
}
class Triangle: Shape
{
public Triangle(int a = 0, int b = 0): base(a, b)
{
}
public override int area()
{
Console.WriteLine("Triangle class area :");
return (width * height / 2);
}
}
class Caller
{
public void CallArea(Shape sh)
{
int a;
a = sh.area();
Console.WriteLine("Area: {0}", a);
}
}
class Tester
{
When the above code is compiled and executed, it produces the following result:
You can redefine or overload most of the built-in operators available in C#. Thus a programmer can use operators with user-defined
types as well. Overloaded operators are functions with special names the keyword operator followed by the symbol for the operator
being defined. Like any other function, an overloaded operator has a return type and a parameter list.
The above function implements the addition operator (+) for a user-defined class Box. It adds the attributes of two Box objects and
returns the resultant Box object.
namespace OperatorOvlApplication
{
class Box
{
private double length; // Length of a box
private double breadth; // Breadth of a box
private double height; // Height of a box
class Tester
{
static void Main(string[] args)
{
Box Box1 = new Box(); // Declare Box1 of type Box
Box Box2 = new Box(); // Declare Box2 of type Box
Box Box3 = new Box(); // Declare Box3 of type Box
double volume = 0.0; // Store the volume of a box here
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
Console.WriteLine("Volume of Box1 : {0}", volume);
// volume of box 2
volume = Box2.getVolume();
Console.WriteLine("Volume of Box2 : {0}", volume);
// volume of box 3
volume = Box3.getVolume();
Console.WriteLine("Volume of Box3 : {0}", volume);
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result:
The following table describes the overload ability of the operators in C#:
Operators Description
+, -, !, ~, ++, -- These unary operators take one operand and can be overloaded.
==, !=, <, >, <=, >= The comparison operators can be overloaded
Example:
In the light of the above discussions, let us extend the preceding example, and overload few more operators:
using System;
namespace OperatorOvlApplication
{
class Box
{
private double length; // Length of a box
private double breadth; // Breadth of a box
private double height; // Height of a box
}
class Tester
{
static void Main(string[] args)
{
Box Box1 = new Box(); // Declare Box1 of type Box
Box Box2 = new Box(); // Declare Box2 of type Box
Box Box3 = new Box(); // Declare Box3 of type Box
Box Box4 = new Box();
double volume = 0.0; // Store the volume of a box here
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
Console.WriteLine("Volume of Box1 : {0}", volume);
// volume of box 2
volume = Box2.getVolume();
Console.WriteLine("Volume of Box2 : {0}", volume);
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result:
Box 1: (6, 7, 5)
Box 2: (12, 13, 10)
Volume of Box1 : 210
Volume of Box2 : 1560
Box 3: (18, 20, 15)
Volume of Box3 : 5400
Box1 is not greater than Box2
Box1 is less than Box2
Box1 is not greater or equal to Box2
Box1 is less or equal to Box2
Box1 is not equal to Box2
Box3 is equal to Box4
3 Employee objEmp = new Employee(009, "Questpond");
5 PassReferenceByRefernce(ref objEmp);
7 }
Display output for above result as follows.
So when we pass a reference type as reference "Employee emp" using 'ref' keyword to a method "PassReferenceByRefernce"
object changes. The effect of passing reference type as reference is that any change to the object inside the method is also
reflected outside in the calling method or main method.
We can use generic collections in our code by calling the namespace "using System.Collections.Generic".
Generic Collections helps us to create flexible type-safe, strong type collections at compile time.
Generic collections helps us to separate the collection logic (Add, Search, Remove, Clear) from different data-types available in .net.
There are already different types of dotnet collections available in .net like array, arraylist, hashtables and specialized collections (string
collections, hybrid collections) each of these collections have their own strong point and weak point.
For example:
Arrays are strong types so there are no boxing and unboxing but weak point of this is it of fixed length size means it is not flexible.
Arraylists and Hashtables are flexible in size but they are not strong type collections, we can pass any data-type objects to it, means there are lots
of boxing and unboxing which means slow in performance.
So by keeping in this mind dotnet development team has brought Generic Collections which bridges advantages of both strong type and
dynamically resize and at a same time to pass any data-type to collections logic.
List collection are strong type index based collection and dynamically resizable and at a same time we can pass any data type to a list object. It
provides many inbuilt methods to manipulate list object. List generic collections is a generic concept applied over Arrays and Arraylist.
Syntax
Where "T" generic parameter you can pass any data-type or custom class object to this parameter.
Example
01 using System;
02 using System.Collections.Generic;
03 using System.Linq;
04 using System.Text;
05
06 namespace GenericCollections
07 {
08 class Program
09 {
11 {
12
14
15 list.Add(1);
16 list.Add(2);
17 list.Add(9);
18
20 {
21 Console.WriteLine(numbers);
22 }
23
25 Console.WriteLine("\n-------------------------------------------\n");
26
28
29 list1.Add(false);
30 list1.Add(true);
31 list1.Add(true);
32 list1.Add(false);
33
35 {
36 Console.WriteLine(booleans);
37 }
38
40 Console.WriteLine("\n-------------------------------------------\n");
41
43
44 list2.Add("Khadak");
45 list2.Add("Shiv");
46 list2.Add("Shaam");
47 list2.Add("Pradeep Dhuri");
48
50 {
51 Console.WriteLine(stringnames);
52 }
53
55
56 Console.WriteLine("\n-------------------------------------------\n");
57 }
58 }
59 }
Output
Generic Dictionary in C-sharp
Dictionary is a generic collections which works on key and value pairs. Both key and value pair can have different data-types or same data-types
or any custom types (i.e. class objects). Dictionary generic collections is a generic concept applied over Hashtable and it provides fast lookups
with keys to get values.
Syntax
Where "TKey" and "TValue" are generic parameters you can pass any data-type or custom class object to this parameters.
01 using System;
02 using System.Collections.Generic;
03 using System.Linq;
04 using System.Text;
05
06 namespace GenericCollections
07 {
08 class Program
09 {
11 {
12
13
15 animaldictionary.Add("Tiger", 3);
16 animaldictionary.Add("Lion", 2);
17 animaldictionary.Add("Panda", 1);
18
19
21 {
24
25 Console.WriteLine("\n-------------------------------------------\n");
26
28 {
30 }
31
32
33
34
35 }
36 }
37 }
Output
Generic Stack and Queue is a concept applied over dot net collection stack and queue. Generic Stack and Queue naming coventions are similar to
dot net collection stack and queue but it has got additional generic parameter "" to pass any data-type. Generic Stack will represents a last-in-first-
out (LIFO) principle from collection of objects and Generic Queue will represents a first-in, first-out (FIFO) principle from collection of objects.
Means when you remove any item from generic stack collections then the last or recently or new added item will be removed first like it will
work in reverse order. While when you remove any item from generic queue collection then the first added item will be removed from generic
queue collections.
Stack works on (Last in first out principle - LIFO) on principle and uses "Push()" method to add items to the collections and "Pop()" method to
remove any item from the collections.
Queue works on (First in First out - FIFO) principle and uses "Enqueue()" method to add items to the collections and "Dequeue()" method to
remove any item from the collections.
Syntax
Example
01 using System;
02 using System.Collections.Generic;
03 using System.Linq;
04 using System.Text;
05
06 namespace GenericCollections
07 {
08 class Program
09 {
11 {
12
13 //Declaring Stack
15 stacknum.Push(1);
16 stacknum.Push(2);
17 stacknum.Push(3);
18 stacknum.Push(5);
19 stacknum.Push(6);
20
21
22
24 {
26 }
27
stacknum.Pop(); //It will remove last/recent added element from the collections i.e
28
(6)
29
30
31 Console.WriteLine("\n-------------------------------------------\n");
32
33 //Declaring Stack
35 stacknames.Push("Pradeep Dhuri");
36 stacknames.Push("Shiv Prasad");
37 stacknames.Push("Khadak");
38 stacknames.Push("Shaam");
39
40
42 {
44 }
45
stacknames.Pop(); //It will remove last element/recent added element from the
46
collections i.e. Shaam
47
48 Console.WriteLine("\n-------------------------------------------\n");
49
50
51 //Declaring Queue
53 Queuenum.Enqueue(1);
54 Queuenum.Enqueue(2);
55 Queuenum.Enqueue(3);
56 Queuenum.Enqueue(5);
57 Queuenum.Enqueue(6);
58
59
60
62 {
64 }
65
66 Queuenum.Dequeue(); //It will remove first element from the collections i.e (1)
67
68
69 Console.WriteLine("\n-------------------------------------------\n");
70
71
72 //Declaring Queues
74 Queuenames.Enqueue("Mohan Aiyer");
75 Queuenames.Enqueue("Shiv Prasad");
76 Queuenames.Enqueue("Khadak");
77 Queuenames.Enqueue("Shaam");
78
79
81 {
83 }
84
Queuenum.Dequeue(); //It will remove first added element from the collections i.e
85
Pradeep Dhuri
86
87 Console.WriteLine("\n-------------------------------------------\n");
88
89
90
91 }
92 }
Generics in C# allows us to create classes and methods with the type as the parameter (which are type-safe).They allow us the
designing of classes and methods with type parameters and whose types are specified only at the time of instantiation. When
these types are instantiated CLR compiles at compile time and stores information related to the generic types.
Generics are different from generic collections.Generic collections are emerged from generic concept. It helps us to maximize
code reuse, performance and type safety.
Generics helps to decouple the data-type from the logical code snippet which makes the code to reuse again and again.
We can also create classes and pass to it the generic parameter as type.
We can use generics in our code by calling the namespace "using System.Collections.Generic;".
Syntax
2 {
3 ......
4 }
Where is a generic parameter, we can pass any data type to this parameter.
Generics in c# example
01 usign System;
02 using System.Collections.Generic;
03
05 {
06 private T a;
07 privateT b;
08
09 public GenericsClass(T x, T y)
10 {
11 a = x;
12 b = y;
13 }
14
16 {
17 if (a.Equals(b))
18 {
19 return true;
20 }
21 else
22 {
23
24 return false;
25 }
26 }
27 }
28
29
30 class Program
31 {
33 {
34
37
40
41
44
47
48
51
52
55
58
59
62
63 }
64 }
In this example of code, I have separated the data-type from the class code and data-type will be decided on compile time. Class
code is flexible that we can pass any data-type and at a same time will maintain type-safety and performance.
As you see from above the code that we have created a custom generic class called "GenericsClass" with generic parameter ""
and a constructor which takes the two input values (Datatype of those values will be decided on compile time) and assign it to
private variables.
Now in the next step we have created boolean method "CompareResult()" which compares the both variables are equal or not
according to that it returns the result.
In the final step, I have just created the objects of "GenericsClass" in the main "Console Application Program" and replaced the
generic parameter with the data-type.
As you see class "GenericsClass" is so flexible that we can attach any data-type and automatically it will function according to
that data-type and with maintaining the type-safety and performance.
Output
When To Use
Generics helps to separate the data-type from the logical code i.e. from methods and classes. So if you want to maximize your
code resuability and maintain its type safety, and performance then use generics.
Generics acts as a bridge between dot.net data-types and your custom logical code and provides flexibility to maximize the code
resuability and reduces code.
C# is a modern language which enables the developer to build a robust application or web application in quick and easy way.
It is a comprehensive language with many advanced features, especially in version 2.0 such as generics.
C# is Type Safe Language. A programming language is type safe when the language defines the behavior or certain rule set of
permission for when the programmer treats a value as a type to which it does not belong.
For Example
Above example will cause an error for all statements because we cannot add string to integer (cannot implicitly covert type string
to int) same way for integer to string and double to int and so on.
The C# language compilers always produce type safe code, which is verified to be type safe during JIT compilation.
Type safe code can access only the memory locations that it has permission to execute.
Type safe code cannot read or access values of the private members from another object’s scope
It accesses types only in well-defined, allowable ways, thereby preventing overrun security breaches.
Type safety helps isolate objects from each other and therefore helps protect them from inadvertent or malicious corruption. This
isolation helps ensure that assemblies cannot adversely affect each other and it increases application reliability.
When a code runs on CLR (Common Language Runtime) it performs the type safe check called type safe verification and this is
done during Just in Time Compilation (JIT) by a tool called peverify.exe.
C# includes native support for the COM and windows based applications.
C# allows us to use pointers as unsafe code blocks to manipulate our old unsafe code. Unsafe code for example accessing
Microsoft word.
C# can directly access components from vb.net and from other managed code languages runs on CLR.For example if we write a
program in VB.NET that program we can access it in C# too by using DLL of vb.net program.
To check c# is an inter operability we will do a simple experiment
Step 1
Step 2
We will add new Visual Basics Class Library (VB Language) project to our Console Application.
Step 3
We will create a simple class "ClsVBNET" and a simple Add() function which takes two input parameter in our VB project as
shown in below snippet of code.
1 //VB code
3 Dim i As Integer
5 i = z + k
6 Return i
7 End Function
8 End Class
Step 4
Now we will call VB code class "ClsVBNET" in our Console Application which is using language as C# as shown below.
01 //C# code
03
04
06 int answer = 0;
08 answer = objvbnet.Add(5,4);
10 }
Step 5
Displaying Output i.e. 5 + 4 = 9
C# Versionable
In simple words we can upgrade code of an existing running application (i.e. creating a new "DLL" with new version) and that
upgraded code we can deploy in the same application without any conflict with the old existing code (Since old code is using
different or old version).
We can have different versions of the same component at the same time and our applications will know automatically which
version to use and what version not to use.
Note: Versioning is done only on assemblies with strong names.
Discuss Boxing and Unboxing in the context of value types and reference types
About Boxing:
About UnBoxing:
Value Types
A data type is a value type if it holds the data within its own memory allocation. Value Types get allocated on stack.
Value Types: Boolean, Char, and Date, SByte, Short, Integer, Long, Byte, UShort, UInteger, or ULong, Struct
Reference Types
A reference type contains a pointer to another memory location that holds the data. Reference Types get allocated on heap.
Reference Types: Class, Objects and All arrays, even if their elements are value types.
With Boxing and Unboxing one can link between value-types and reference-types by allowing any value of a value-type to be
converted to any value of a reference-type and vice versa.
2 {
4 {
5 int A = 5;
6 object B = A;//Boxing
7 }
8 }
As you see in our above code that we have converted value type "int A" with value 5 to reference type "object B" by assigning
value type to reference type object.
2 {
4 {
5 int A = 5;
6 object B = A;//Boxing
8 }
9 }
As you see in our above code that we have converted reference type "object B" with reference value 5 to value type "Int C" by
assigning reference type object to value type.
To check with a valid proof of boxing and unboxing you can check above code i.e. compiled code "dll" or "exe" file using
"ILDASM" tool.ILDASM tool which shows half partially compiled code i.e. IL code or Intermediate Language Code.
Visual Studio Command Prompt : Get in visual studio tools inside your program files.
So this is all about boxing and unboxing if you have any query regarding this topic kindly let me know through your comments.
if you like this article share it with your friends.
_______________________________________________________________________________________________
Understanding Switch Statement with the help of an
example
About Switch Statement
Switch statement is form of control selection statements. Switch statement is a set of statements (Like if Statements) from which
any one statement is executed depending on Condition or Boolean expression.
Syntax
1 switch (expression)
2 {
3 case expression:
5 break;//Jump Statement
6 default:
8 break;
9 }
For Example
1 switch (condition){
2 case "Add":
4 break;//Jump Statement
5 default:
6 int add = 0;
7 break;
8 }
Body of the case statement will execute only if Boolean condition matches to the case expression (If True).
01 using System;
02 using System.Collections.Generic;
03 using System.Linq;
04 using System.Text;
05 namespace Practical2b
06 {
07 class Program
08 {
10 {
11 ……///code snippet
12 }
13 }
14 }
In this step we will ask input value from an user to execute (Add or Subtract or Multiplication or Division).
4 }
8 }
In this step we will create switch statement with different cases of mathematical like Add, Sub, Multiply and Division and with
Boolean condition.
Add - It will add two numbers with display output and finally jump statement (break).
Sub - It will subtract two numbers with display output and finally jump statement (break).
Mul - It will multiply two numbers with display output and finally jump statement (break).
Div - It will divide two numbers with display output and finally jump statement (break).
02 {
05
08
09 switch (condition){
10
11 case "Add":
13 break;
14 case "Sub":
15 Console.WriteLine("Substract number, {0}", num1 - num2);
16 break;
17 case "Mul":
19 break;
20 case "Div":
22 break;
23 default:
25 break;
26
27 }
28 }
An indexer provides array like syntax. It allows a class to be accessed the same way as an array is access means object of a class
be indexed same way as an array. Modifier of an indexer can be of public, private, protected and internal.The return type can be
any valid C# types.
Syntax of an Indexer
1 public string this[int parameter]{
2 Get{
4 }
5 Set{
7 }
8 }
So this is about an indexer. Now let go and see how an indexer is different from a property.
1st Difference
Indexers are created by using "this" keyword and identified by its signature.
For example
2 Get{
4 }
5 Set{
7 }
8 }
Above snippet shows an indexer code with "string" as return type and followed by "this" keyword and "int" as input parameters.
2 Get{
4 }
5 Set{
7 }
8 }
Above snippet shows a property code with "string" as return type and followed by property name "EmployeeName".
2nd Difference
Indexer example
01 class clsEmployee{
04 {
05 get{
06 return emplcodes[code];
07 }
08 set{
09 emplcodes[code] = value;
10 }
11 }
12 }
13 class Program{
15
21
22 }
Above snippet shows a class "clsEmployee" which has got an indexer of string array values and in our main program method we
have created object of a class and now indexers are accessed by class instance or object using an index value as shown in the
above code.
Property Example
01 class clsEmployee{
04 {
05 get{
06 return _emplname;
07 }
08 set{
09 _emplnam = value;
10 }
11 }
12 }
13 class Program{
14
16
18 empl.EmployeeName = “Shaam”;
19 }
20
21 }
Above snippet shows a class "clsEmployee" which has got a property "EmployeeName" of string type and in our main program
method we have created object of a class and now properties are accessed by class instance or object using a property name
shown in the above code.
3rd Difference
A get and set accessors of an indexer has the same formal parameter list as the indexer.
A get accessor of a property has no parameters and a set accessor of a property contains the implicit value parameter.
Checked and unchecked are operators of C#. Checked and Unchecked operators enforce CLR (Common Language Runtime) to
handle stack overflow control.These operators checks code block which can cause overflow in an application.
Checked Operators
The checked operator evaluates a block of code in a checked context and enforces overflow through an exception if an overflow
occurs.
3 checked{
6 }
8 }
Unchecked Operators
The checked operator evaluates a block of code in an unchecked context and does not through overflow exception if an overflow
occurs.
Sometimes it might through negative integral output or wrong output (in terms of calculation).
3 unchecked{
6 }
8 }
Now let's demonstrate a simple example using console application. In this example we will use int (Int32) variable to check
overflow in an application.
1 class Program
2 {
4 {
6 }
7 }
For this step we will use integer variable "inttestVariable" and assign a highest value to it i.e. highest Int32 bit value which is
2147483647.
1 class Program
2 {
4 {
7 }
8 }
To test your "int" size, type i.e. whether its 32 bit or 64 bit and range you can use operator
Typeof - Get the type of a data type.
Sizeof - Get the total size of a data type.
Minvalue - Get minimum value of a data type
Maxvalue - Get maximum value of data type.
1 class Program
2 {
4 {
6 }
7 }
Now coming back to checked and unchecked operator. Next step let’s use checked operator and increment the default value of an
integer variable "inttestVariable" in the code block of checked operator.
01 class Program
02 {
04 {
07
08 checked{
09
10 Console.WriteLine("\n");
11 inttestVariable++;
13
14 }
15
16 }
17 }
If you see above code we have incremented the integer value by +1 means it's an overflow in an application. Because the
maximum value of integer is 2147483647.It will cause a stack overflow exception error. Let's display output and see the error.
Display Output
Now let's change the operator replacing checked with unchecked and check the output.
01 class Program
02 {
04 {
07
08 unchecked{
09
10 Console.WriteLine("\n");
11 inttestVariable++;
13
14 }
15
16 }
17 }
As you see from above code block of unchecked operator is that it does not thrown an exception error but it has shown negative
output or wrong in calculation.
So it is conclude that checked operator checks the block of code if arithmetic calculation or value is overflow in an application
then it will throw up an overflow exception error while unchecked operator does not throw up overflow exception error.
C# Structures are useful for small data structures like having value semantics for creating a graph points and many more such
areas where you can apply structures.
Syntax
1 struct StructName{
2 ……Code
3 }
For Example
1 struct MalingList
2 {
So this is all about structures in c-sharp. Now let's go and understand about classes.
What is a Class?
Syntax
1 class className{
2 ……Code
3 }
For Example
1 class MalingList
2 {
8 }
Stack- It holds value type variables plus return addresses for functions. All numeric types, ints, floats and doubles along with
enums, chars, bools and structs are value types.
Heap- The heap hold variables created dynamically known as reference variables and mainly instances of classes or strings.
Value Types - A data type is a value type if it holds the data within its own memory allocation.
Reference Types - A reference type contains a pointer to another memory location that holds the data.
Differentiate between structures and classes
1st Difference
2nd Difference
3rd Difference
It terms of memory consumption structs takes less memory as same compared to classes.
It terms of memory consumption classes takes more memory as same compared to structs.
Now let's demonstrate structures and classes by checking the memory consumption of classes and structures on stack and heap.
1st Step
First step create a windows form application project and then drop a single button on Form 1 of windows screen as shown below.
2nd Step
Second step on a separate CS file create a structure "strGraph" with two properties of "int" data type as shown below.
02
05 public int X{
07 set { _x = value; }
08 }
09 public int Y{
11 set { _y = value; }
12 }
13
14 }
3rd Step
Third step again on a same CS file create class "clsGraph" with two properties of "int" data type as shown below.
02
05 public int X{
07 set { _x = value; }
08 }
09 public int Y{
11 set { _y = value; }
12 }
13
14 }
The structures in C# seems too similar to classes. But they are two entirely different aspects of the language.
4th Step
Fourth step we will go back to our Form 1 double click on a button Form 1 CS file will open there on button click event we
will create loop of 100 * 1000 times using FOR Loop as shown below.
5 }
7 }
Now first we will create an object of structure in For Loop and try to record memory usage using CLR Profiler as shown below.
CLR Profiler - It's a tool and it is been used to check memory consumption of each object been used in an application or
website.You can download this tool from an official site of microsoft http://www.microsoft.com/en-in/download/default.aspx
5 }
7 }
Click on start application then select windowns application exe (your project exe) after that program will run automatically then
click on the button on the form and close the application then automatically CLRProfiler will create a report as shown below.
As you can see from above screen shot in Allocated bytes structure has consumed 400,956 bytes of memory on stack.
Now let's repeat the same process for class we will create a class object in FOR Loop as shown below.
5 }
7 }
So now using our CLR Profiler let's check the output of memory consumption of a class.
As you can see from above screen shot in Allocated bytes class has consumed 3,600,344 bytes of memory.
It terms of memory consumption structs takes less memory as same compared to classes.
It terms of memory consumption classes takes more memory as same compared to structs.
A data type is a value type if it holds the data within its own memory allocation.
All numeric data types like Boolean, char, date, int and struct all are value types.
All structures are value types, even if their members are reference types.
A Value Type Memory is allocated on stack.
For Example
1 int i = 009;
2 Char ch = "w";
A reference type contains a pointer to another memory location that holds the actual data. In reference types data is not hold
within its own memory allocation it contains reference of another memory location which actually holds the data.
All interfaces, delegates, class objects, arrays and dynamic types all are reference types.
Example 1
Example 2
1 class Employee
2 {
4 }
Integer is a value type but since it's in class scope (reference type).indirectly it also becomes a reference type.
So now that you have understood about value types and reference types let's come back to our main topic on passing parameters.
Passing the value type or reference type can be done through using methods, properties, constructors and indexers.
Pass by value assumes that the variable value is set before the method or function is called.
A variable of reference type contains a pointer to another memory location that holds the data.
To pass a parameter by reference, you can use the 'ref' or 'out' keyword.
Ref:
Pass by reference using 'ref' keyword assumes that the variable value is already set before the function is called.
Out:
Pass by reference using 'out' keyword assumes that the variable value is will be set by calling function.
To keep it simple let's just understand these topics one by one. We will first understand Pass by Value Type and their ways of
passing parameter then Pass by Reference Type and their ways of passing parameter.
For Example:
2 {
3 val *= val;
5 }
In above the code we have created a static method "PassValueByValue" with an input parameter value type. This method squares
the input parameter and displays the output.
To test Pass value types by value we have created a main method which has value type "testval" and initialized to 5 and pass
same input parameter to a method "PassValueByValue" as shown below code.
2 {
3 int testval = 5;
7 }
1 Output // 5 ;
2 PassValueByValue // 25;
So when we pass a value as value type parameter "testval" to a method "PassValueByValue". Parameter "testval" does not
change. Tested value type holds the data within its own memory allocation.
To a method or a function we need to pass value type as reference. To pass reference types we will use the prefix of 'ref' and 'out'
keyword.
For Example:
2 {
5 }
In above the code we have created a static method "PassValueByReferenceByRef" with an input reference type using 'ref'
keyword. This method adds the input parameter by 55 and displays the output.
To test we have created a main method which has value type "testval" and initialized to 5 and pass same input parameter as
reference to a method "PassValueByReferenceByRef" as shown below code.
2 {
3 int testval = 5;
5 PassValueByReferenceByRef(ref testval);
7 }
1 Output // 5 ;
2 PassValueByReferenceByRef // 60;
So when we pass a value as reference type parameter “testval” to a method "PassValueByReferenceByRef". Parameter
"testval" changes. The effect of passing parameter by reference is that any change to the parameter inside the method is also
reflected outside in the calling method or main method.
Same way we repeat same procedure by using 'out' keyword. So this is all about Pass by Value Type.
As we all know that reference type's means dynamic data types for dynamic allocation of data like class objects, arrays, and
interfaces and so on this can hold dynamic values as reference.
For this example let's create a simple class "Employee" with Employee Name and Employee Code as shown in below snippet of
code.
02
06 {
07 EmployeeCode = emplcode;
08 EmployeeName = emplname;
09 }
10
11 }
Now let's create an object in Main method of a program and pass some input values as shown below.
2 {
5 }
For Example:
2 {
4 emp.EmployeeCode = 8;
6 }
In above the code we have created a static method "PassReferenceByValue" with a input parameter as class object "Employee
emp". This method assigns the new values to object and displays the output.
To test Pass reference types by value we have created a main method in which we have already created the "Employee" object
and assign values to both "EmployeeName" and "EmployeeCode" via constructor and passes the same object reference as
input value to a method "PassReferenceByValue" as shown in below code.
2 {
5 PassReferenceByValue(objEmp);
So when we pass a reference type as value "Employee emp" to a method "PassReferenceByValue" object changes. The effect of
passing reference type as value is that any change to the object inside the method is also reflected outside in the calling method or
main method.
To a method or a function we need to pass reference types as reference. To pass reference types we will use the prefix of 'ref' and
'out' keyword.
For this we will use same example as used in Pass reference type as Value (Employee Class).
Now let’s create an object in Main method of a program and pass some input values as shown below.
2 {
5 }
To a method or a function we need to pass reference type as reference. To pass reference types we will use the prefix of ‘ref’
keyword.
For Example:
2 {
4 emp.EmployeeCode = 7;
6 }
In above the code we have created a static method "PassReferenceByRefernce" with an input parameter as class object
"Employee emp". This method assigns the new values to object and displays the output.
To test Pass reference types by reference we have used ‘ref’ keyword and we have created a main method in which we have
already created the "Employee" object and assign values to both "EmployeeName" and "EmployeeCode" via constructor and
passes the same object reference as input value to a method "PassReferenceByRefernce" as shown in below code.
2 {
5 PassReferenceByRefernce(ref objEmp);
7 }
So when we pass a reference type as reference "Employee emp" using 'ref' keyword to a method "PassReferenceByRefernce"
object changes. The effect of passing reference type as reference is that any change to the object inside the method is also
reflected outside in the calling method or main method.
Sealed modifier restricts the inheritance feature of an object oriented programming means sealed classes cannot be inherited or
implemented further to any classes. To implement sealed classes in programs we need to use "sealed" keyword before the
"class" keyword.
When sealed modifier is applied to a method then it prevents a method from being overloaded in further classes.
1 sealed class Employee ///Sealed class
2 {
4 }
2 {
5 }
6 }
In above the code we have class "Employee"with "sealed" type modifier and simple "DisplayEmployeeDetails" method which
displays employee details.
To perform this test we will create a main program of console with static main method. Now let's try to inherit the
"Employee" class to our main program as shown in below code.
As you can see when we tried to build the application we got following error which states that we cannot derive from sealed
type member but we can aggregate the "Employee" class with sealed type modifier in our main method as shown in below
code.
So when we try to call "DisplayEmployeeDetails" method through the object "objEmp" we could find
"DisplayEmployeeDetails" method as shown in above code.
Constructor is a method which gets executed automatically when we create or instantiate object of that class having constructor.
A single class can have multiple constructors means we can have more than one constructor in a class. It is also called as
overloaded constructor.
A benefit of using a constructor is that it guarantees that the object will go through a proper initialization before an object being
used means we can pre-initialize some of the class variables with values before an object being used.
Constructors do not have any return types means. So there is no return type.
A constructor can be called another constructor by using "this" keyword. "this" keyword is the current instance of a class.
Syntax of a Constructor
Constructors are declared by using the same class name without any return type. An example is shown below.
1 class clsAddition{
3 public clsAddition(){
5 }
6 }
Types of Constructors in C#
Default Constructor
Parameterized Constructor
Copy Constructor
Static Constructor
Private Constructor
Default Constructor
A constructor without any parameters is called as default constructor means a constructor which does not have any input
parameter is known as default constructor.
02
04 public clsAddition(){
05 Mycode = 9;
06 }
07 }
08
09 class Program{
10
14 }
15 }
Parameterized Constructor
A constructor having one or more parameters is called as parameterized constructor means a constructor which is having single
input parameter or multiple input parameters of same data types or different data types are known as parameterized constructor.
02
04 public int x = 0;
05 public int y = 0;
07 itype = type;
08 x = a;
09 y = b;
10 }
11 }
12
13 class Program{
14
20
21 }
22 }
Copy Constructor
A constructor that contains a parameter of same class type is called as copy constructor.
C# does not provide a copy constructor. A copy constructor enables you to copy the data stored in the member variables of an
object of the class into another new object means it helps to copy data stored in one object into another new object of the same
instance.
01 class Car
02 {
06
08 {
09 _nameofcar = NameofCar;
10 _carno = CarNumber;
11 _carprice = CarPrice;
12 }
13
14 //Copy Constructor
17 _nameofcar = objCar._nameofcar;
18 _carno = objCar._carno;
19 _carprice = objCar._carprice;
20 }
21
22
23 }
24
25 class Program
26 {
28 {
34
35 }
36 }
Static Constructor
Static constructor should be parameter less means it should not contain any input parameter. Program will not execute if static
constructor is having any input parameter.
Static constructor can be invoked once for any number instances are created and it is invoked only during the first initialization of
instance. It is used to initialize static fields of the class
1 class clsAddition{
2
3 static clsAddition(){
5 }
6 }
02 {
03
04 private int a = 0;
05 private int b = 0;
07
09 {
10 a = x;
11 b = y;
12 }
13
14 static clsAddition()
15 {
17 _counter++;
19 }
20
21 public clsAddition()
22 {
23 a = 150;
24 b = 160;
25 }
26
27
29 {
31 }
32
33
34 }
35
36
37 class Program
38 {
40 {
41
43 clsAddition._counter = 9;
44 objadd.Display();
45
47
49 objadd.Display();
50
51 }
52 }
If you see in this example we have created instances 2 times and at a same time we tried to change the counter value but on the
output if you see it is showing the same value as it was assigned during the first initialization process in the static constructor.
So it is concluded that static constructor can be invoked once for any number instances are created and it is invoked only during
the first initialization process.
Private Constructor
We cannot create an object of the class which is having a private constructor. Program will not allow us to create an object of a
class having private constructor.
A long with private constructor we can have a public constructor (overloaded constructor but not of the same type).
To access the methods or properties in a class with private constructor we can assign methods or properties with "static"
keyword.
02 {
03
05 private clsEmployee()
06 {
07
08 }
09
10
11 }
12
13 class Program
14 {
16 {
17
19
20 }
21 }
An interface looks like a class but has got no implementation. In an interface we cannot do any implementation but we can
declare signatures of properties, methods, delegates and events.
Implementation part is been handle by the class that implements the interface. Implemented interface enforces the class like a
standard contract to provide all implementation of interface members.
We can implement single interface or multiple interfaces to the class. By default interfaces are public.
1 interface IEmployee{
3 void DisplayEmployeeDetails();
4
5 }
Above syntax shows simple demonstration of interface "IEmployee" with signature of a method "DisplayEmployeeDetails".
Now let's implement the same interface to a class.
2 {
5 }
7 }
As you see in our above snippet of code that implementation of an interface method signature is done by the class which
implemented that interface.
Implemented interface enforces the class like a standard contract to provide all implementation of interface members.
In architecting the project we can define the proper naming conventions of methods, properties in an interface so that while
implementing in a class we use the name conventions.
Explicit
Implicit
To implement an interface explicitly we have to define an interface name followed by (".") dot operator then the method name.
2 {
3 void IEmployee.DisplayEmployeeDetails()
4 {
6 }
7 }
When you put a dot operator after an interface name you will see all the signatures defined in an interface.
When we have two different interfaces with same method name then in that scenario we can use explicit interface
implementation.
2 void DisplayEmployeeDetails();
3 }
6 void DisplayEmployeeDetails();
7 }
In the above code we have two different interfaces "IEmployee" and "ICompany" with same method name. Now let's implement
these two interfaces to a class "clsEmployee" as shown in below snippet of code.
2 {
6 }
In order to implement an interface explicitly we have to define the interface name followed by (".") dot operator before method
name as shown in below snipped code.
2 {
3 void ICompany.DisplayEmployeeDetails(){
5 }
6 void IEmployee.DisplayEmployeeDetails(){
8 }
9 }
Console Application
Finally let's create the objects of two interfaces "IEmployee" and "ICompany" in our main method of a Console Application
program.
01 class Program{
02
04 {
06 IEmp.DisplayEmployeeDetails();
07
09 IComp.DisplayEmployeeDetails();
10 }
11
12 }
Let's run the application (Ctrl + F5) and display the output as shown it below.
To implement an interface implicitly we have to implement the interface name before the class using colon ":" operator as shown
in below snipped code.
2 {
4 {
6 }
7 }
When you put a colon after a class name you will see the custom defined and as well as system defined interfaces in the program.
Example of Implicit Interface
1 interface IEmployee
2 {
3 void DisplayEmployeeDetails();
4 }
Above code shows simple demonstration of an interface "IEmployee" with signature of a method "DisplayEmployeeDetails".
Now let's create a class "Employee" and implement the interface implicitly as shown in below snippet of code.
2 {
4 {
6 }
7 }
Console Application
Finally let's create the objects of an interface "IEmployee" in our main method of a Console Application program.
4 {
7 }
9 }
Let's run the application (Ctrl + F5) and display the output as shown it below.
Polymorphism is one of the principle of object oriented programming. "Poly" means many and
"morph" means forms hence the name polymorphism. Polymorphism also refered to as one name
many forms or having one name with multiple functionality.
In simple words you can use same method name with different signature or same signature but in
different class.So depending on a data type it processes objects differently and an ability to
redefine methods for a derived classes.
Static Polymorphism
Dynamic Polymorphism
Static Polymorphism
02 {
03
05 {
06 return a + b;
07 }
08
10 {
11 return z + x + c;
12 }
13
14 }
In above code we have a class "clsCalculation" having two functions with same name "Add" but
having different input parameters.
First function is with 2 parameters and second function having 3 parameters. So this type of
polymorphism is also known as method overloading.
It is a compile time polymorphism because compiler already knows what type object it is linking
to, what are the methods it is going to call it. So linking a method during a compile time also
called as Early binding.
Dynamic Polymorphism
Dynamic polymorphism is also called as Run Time polymorphism. In this type of polymorphism
methods have the same name, same signature but different in the implementation.
In Dynamic polymorphism methods are overridden so it also called as method overriding.
During run time, Method overriding can be achieved by using inheritance principle and using
"virtual" and "override" keyword. so this type of polymorphism can also be called as late
binding.
In late binding compiler doesn't know what kind of methods it has to call and which can be
achieved only during the run time.so it is called as run time polymorphism.
04
06 {
07 return 0;
08 }
09
10 }
11
13 {
14
16 {
18 }
19
20 }
21
23 {
24
26 {
28 }
29
30 }
As you can see from above code that we have one base class "clsShape" with a "virtual" method
"getArea()" and two derived classes "clsCircle" and "clsShape" each having an "override"
method "getArea()" with different implementations.
So that you have understood about Polymorphism, Static Polymorphism and Dynamic
Polymorphism. Now let's see a simple example of polymorphism.
In this example we will illustrate an example of dynamic polymorphism.we will take up above
the example and try to implement it.
02 {
04
06 {
07 return 0;
08 }
09
10 }
11
13 {
14
18 }
19
20 }
21
23 {
24
26 {
28 }
29
30 }
So as you know that we have one base class "clsShape" with a "virtual" method "getArea()"
and two derived classes "clsCircle" and "clsShape" each having an "override" method
"getArea()" but with different implementation.
Now to see the output we will create "Console Application" and try to see the result.
1 class Program
2{
4 {
7 }
8}
In this step we will create base class object and assign it to derived classes.
01 class Program
02 {
04 {
05
08
09 }
10 }
So as you see from above code that we have created two objects "objShape1" for "clsCircle"
and "objShape2" for "clsSphere" respectively.
01 class Program
02 {
04 {
05
11 }
12 }
Step 4 - Output
What We Call
In Inheritance main existing class is called as generalized class, base class, super class and parent
class and the new class created from existing class is called as specialized class, sub class, child
class and derived class. We normally talk in terms of base class and derived class.
Syntax of Inheritance
1 class ParentClass{
5}
9}
Special Character ":" in Inheritance
Inheritance uses special character called ":" colon to make a relationship between parent and
child as you can see in above syntax of code.
When we create a new class and we want to reuse some of the methods or properties from
existing class then that is an ideal time to implement inheritance.
Advantage of Interitance
Types of inheritance in c#
1.Single Inheritance
2.Multilevel Inheritance
3.Multiple Inheritance
4.Hierarchical Inheritance
5.Hybrid Inheritance
Single Inheritance
Single Inheritance means when a single base is been implemented to single derived class is
called as Single Inheritance.Means we have only one parent class and one child class.
Example of Single Inheritance
01 class Company{
02
04
06
07 }
08
10
12
13 }
14
15 }
16
20
22
23 }
24
26
28
29 }
30
31 }
As you can see from the above code that we have implemented single inheritance.
Multilevel Inheritance
When a derived class is created from another derived class or let me put it in this way that a class
is created by using another derived class and this type of implementation is called as multilevel
Inheritance
Example of Multilevel Inheritance
1 class HeadOffice{
7 }
8}
Now let's assume that class "HeadOffice" is our Parent class or Base class. Now in my next step i
will create one derived class.
7 }
9}
So as you can see that i have created a derived class "BranchOffice" by implementing the class
"HeadOffice" to it.
It means now we have one parent class and one derived class. In the next step i will create
another derived class by implementing our existing derived class "BranchOffice" to achieve
multilevel Inheritance.
02
04
06
07 }
08
10
12
13 }
14
15 }
From the above souce code you can see that we have achieved multilevel Inheritance by
implementing one derived class to another derived class. Now the class "Employee" will have
the access of all the properties and methods of class "BranchOffice" and class "HeadOffice".
Multiple Inheritance
Due to the complexity of a code multiple inheritance is not been supported in C# or in DOT.NET
but DOT.NET or C# supports multiple interfaces.
Hierarchical Inheritance
When more than one derived classes are implemented from a same parent class or base class then
that type of implentation is known as hierarchical inheritance.
In short it means single base class having more than one derived classes.
01 class HeadOffice{
02
04
06
07 }
08 }
09
10
12
14
16
17 }
18
19 }
20
22
24
26
27 }
28
29 }
As you can see from above the code that we have one base class "HeadOffice" and two derived
classes "BranchOffice1" and "BranchOffice2" which are implemented from same base class i.e.
"HeadOffice".
Hybrid Inheritance
This is a special type of inheritance and can be achieved from any combination of single,
hierarchical and multi level inheritance known as hybrid inheritance.
In the below code example i have combined hierarchical inheritance and multi level inheritance
together.
02 class HeadOffice{
03
05
07
08 }
09 }
10
11
13
15
17
18 }
19
20 }
21
23
25
27
28 }
29
30 }
02
04
08
09 }
10
12
14
15 }
16
17 }
So that you have understood the inheritance and their 5 types. Now let's a simple example of
inheritance using csharp.
06
08 {
11 }
12
13 public string Gear
14 {
17 }
18
20 {
23 }
24
26 {
29 }
30
32 {
34 }
35
37 {
39 }
40
41
42 }
Above i have created a simple class "Car" with some methods and some properties. Now next
step i will create two classes "SentroCar" and "BCWCar" and implement it with a single base
class "Car"
02 {
03
05 {
07 }
09 {
11 }
12 }
02 {
03
05 {
09 {
11 }
12 }
As you see that we have two derived classes implemented from same base class. This type of
implementation can also be called as Hierarchical Inheritance.
01 class Program
02 {
04 {
05
07 obj.CarPrice();
08 obj.NameofCar();
09
11 obj.CarPrice();
12 obj.NameofCar();
13 }
14 }
//Output
Car Prize is : 2.5L INR
Company Name of this Car is Sentro
Car Prize is : 4.5L INR
Company Name of this Car is BCW.
_______________________________________________________________
We can achieve Encapsulation by using "private" access modifier as shown in below snippet of
code.
1 class Employee{
5 }
7}
Encapsulation means protecting important data inside the class which we do not
want to be exposed outside of the class.
If you have seen important TV machine, TV connections and TV color tube is hidden inside the
TV case which is not been exposed for viewers like us and exposed only neccessary things of a
TV like TV Channel keys, TV volume keys, ON/OFF switch, Cable Switch and TV remote
control for viewers to use it.This means TV machine, TV connections and TV color tube is an
unwanted data and not needed for viewers to see is been hidden from outside the world.
So encapsulation means hiding the important features of a class which is not been needed to be
exposed outside of a class and exposing only necessary things of a class.
Here hidden part of a class acts like Encapsulation and exposed part of a class acts like
Abstraction.
For more information on Abstraction check out this article Abstraction in Csharp with an
example.
02
04
05 Console.WriteLine("Machine of a Television");
06
07 }
08
10
12
13 }
14
16
17 Console.WriteLine("Keys of a Television");
18
19 }
20
23 Console.WriteLine("Remote of a Television");
24
25 }
26
28
30
31 }
32
33 }
So as you can see from our above code that we have hidden core part of a television methods by
using "private" access modifier and exposed only necessary methods for a viewers to use it
using "public" access modifier.
Abstraction is one of the principle of object oriented programming. It is used to display only
necessary and essential features of an object to ouside the world.Means displaying what is
necessary and encapsulate the unnecessary things to outside the world.Hiding can be achieved by
using "private" access modifiers.
Note - Outside the world means when we use reference of object then it will show only
necessary methods and properties and hide methods which are not necessary.
Implementation of Abstraction
To implement abstraction let's take an example of a car. We knows a car, Car is made of name of
car, color of car, steering, gear, rear view mirror, brakes, silencer, exhaust system, diesal engine,
car battery, car engine and other internal machine details etc.
Now lets think in terms of Car rider or a person who is riding a car. So to drive a car what a car
rider should know from above category before he starts a car driving.
1. Name of Car
2. Color of Car
3. Steering
4. Rear View Mirror
5. Brakes
6. Gear
Unnecessary things means not that compulsary to know for a Car rider
Now above same thing let me put in the coding style using C#
05
06 public string NameofCar
07
08 set
09
10 _nameofcar = value;
11 }
12 get
13
14 return _nameofcar;
15 }
16 }
17
18 public string ColorofCar
19
20 set
21
22 _colorofcar = value;
23 }
24 get
25
26 return _colorofcar;
27 }
28 }
29
30 public void Steering()
31
32 Console.WriteLine("Streering of Car");
33 }
34
35 public void RearViewMirror()
36
37 Console.WriteLine("RearViewMirror of Car");
38 }
39
40 public void Brakes()
41
42 Console.WriteLine("Brakes of Car");
43 }
44 public void Gear()
45
46 Console.WriteLine("Gear of Car");
47 }
48
49
50 private void InternalDetailsofCar()
51
52 Console.WriteLine("InternalDetailsofCar of Car");
53 }
54
55 private void CarEngine()
56
57 Console.WriteLine("CarEngine of Car");
58 }
59
60 private void DiesalEngine()
61
62 Console.WriteLine("DiesalEngine of Car");
63 }
64
65 private void ExhaustSystem()
66
67 Console.WriteLine("ExhaustSystem of Car");
68 }
69
70 private void Silencer()
71
72 Console.WriteLine("Silencer of Car");
73 }
74
75
76 }
As you can see from above code that necessary methods and properties exposed by using
"public" access modifier and unnecessary methods and properties (not compulsary) hidden by
using "private" access modifier.
As you see to achieve abstraction we used access modifier "public" to expose some methods and
properties to outside the class or world.
As you see to achieve abstraction we used access modifier "private" to hide some methods and
properties from outside the class or world.
Finally lets check by creating an object of above class "Car" in our main program of a console
application and by using object lets see weather we are getting all exposed necessary methods
and properties.
1 class Program
2
3 static void Main(string[] args)
4
5 Car objCar = new Car();
6
7 }
8}
Conclusion
Sucessfully we have exposed necessary methods and properties to outside the world or class.
This is how we need to implement abstraction or we can achieve abstraction in our code or
application.
Abstract classes that cannot be instantiated mean we cannot able to create an object of an abstract
class but abstract class can be implemented to child classes like a common base class. An
abstract class can be partially implemented or not at all implemented.
Syntax
3}
Abstract Method
In an abstract class a method which has a keyword "abstract" and doesn't provide any
implementation is called abstract method.The implementation logic of abstract methods is
provided by the child classes or derived classes.Child classes use keyword "override" with same
method name (as abstract method name) to provide further implementation of abstract methods.
In an abstract class a method which doesn't have a keyword "abstract" and provide any
implementation is called non abstract method.
Abstract class enforces derived classes to provide all implementation logic for abstract methods
or properties.
Use abstract class when you want to create a common base class for a family of types and with
some implementation
Subclass only a base class in a hierarchy to which the class logically belongs.
Below a simple example in c# which illustrates abstract class with abstract methods and non
abstract methods.
First step lets create an abstract class "absCalculate" having abstract methods and non abstract
methods.
02
05
07 }
08
11 }
Now next step lets create a class "clsCalculate" and implement it with abstract class
"absCalculate".
1 class clsCalculate:absCalculate
3 ...code
4 }
When we build this application we got the following error because we have not provided
implementation of an abstract method as you can see it in above snapshot.
Now lets give implementation for an abstract method using override keyword implementing the
abstract method as you can see in our below code.
1 class clsCalculate:absCalculate
8 }
9}
Finally lets create an object of class "clsCalculate" in our main program of an console application
and see the output.
view sourceprint?
01 class Program
02
03
05
06
09
12
17 }
18 }
Output