0% found this document useful (0 votes)
7 views

C#Practical Examples

The document provides an overview of key concepts in object-oriented programming (OOP), including encapsulation, abstraction, inheritance, polymorphism, and interfaces. It explains various access specifiers in C#, such as public, private, protected, internal, and protected internal, along with examples demonstrating their usage. Additionally, it covers method overloading and overriding as forms of polymorphism, and the role of abstract classes in providing partial implementations of interfaces.

Uploaded by

cavenmat
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

C#Practical Examples

The document provides an overview of key concepts in object-oriented programming (OOP), including encapsulation, abstraction, inheritance, polymorphism, and interfaces. It explains various access specifiers in C#, such as public, private, protected, internal, and protected internal, along with examples demonstrating their usage. Additionally, it covers method overloading and overriding as forms of polymorphism, and the role of abstract classes in providing partial implementations of interfaces.

Uploaded by

cavenmat
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 108

Encapsulation is defined 'as the process of enclosing one or more items within a physical or logical package'.

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

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.

The following example illustrates this:

using System;

namespace RectangleApplication
{
class Rectangle
{
//member variables
public double length;
public double width;

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 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, 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

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.

The following example illustrates this:

using System;

namespace RectangleApplication
{
class Rectangle
{
//member variables
private double length;
private double width;

public void Acceptdetails()


{
Console.WriteLine("Enter Length: ");
length = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Enter Width: ");
width = Convert.ToDouble(Console.ReadLine());
}
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 ExecuteRectangle
{
static void Main(string[] args)
{
Rectangle r = new Rectangle();
r.Acceptdetails();
r.Display();
Console.ReadLine();
}
}
}

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

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

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.

The following program illustrates this:

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.

Protected Internal Access Specifier

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:

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;

namespace InterfaceApplication
{

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();
}
}
}

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.

Base and Derived Classes

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.

The syntax used in C# for creating derived classes is as follows:

<acess-specifier> class <base_class>


{
...
}
class <derived_class> : <base_class>
{
...
}

Consider a base class Shape and its derived class Rectangle:

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);

// Print the area of the object.


Console.WriteLine("Total area: {0}", Rect.getArea());
Console.ReadKey();
}
}
}

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

Total area: 35

Base Class Initialization

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;
}

// Base class PaintCost


public interface PaintCost
{
int getCost(int area);

}
// 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.

In Polymorphism we have 2 different types those are

- Overloading (Called as Early Binding or Compile Time Polymorphism or static binding)

- Overriding (Called as Late Binding or Run Time Polymorphism or dynamic binding)

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.

Please note the following rules about abstract classes:

 You cannot create an instance of an abstract class


 You cannot declare an abstract method outside an abstract class
 When a class is declared sealed, it cannot be inherited, abstract classes cannot be declared sealed.

The following program demonstrates an abstract class:

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:

Rectangle class area :


Area: 70

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.

Dynamic polymorphism is implemented by abstract classes and virtual functions.

The following program demonstrates this:

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
{

static void Main(string[] args)


{
Caller c = new Caller();
Rectangle r = new Rectangle(10, 7);
Triangle t = new Triangle(10, 5);
c.CallArea(r);
c.CallArea(t);
Console.ReadKey();
}
}
}

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

Rectangle class area:


Area: 70
Triangle class area:
Area: 25

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.

For example, look at the following function:

public static Box operator+ (Box b, Box c)


{
Box box = new Box();
box.length = b.length + c.length;
box.breadth = b.breadth + c.breadth;
box.height = b.height + c.height;
return box;
}

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.

Implementation of Operator Overloading

The following program shows the complete implementation:


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

public double getVolume()


{
return length * breadth * height;
}
public void setLength( double len )
{
length = len;
}

public void setBreadth( double bre )


{
breadth = bre;
}

public void setHeight( double hei )


{
height = hei;
}
// Overload + operator to add two Box objects.
public static Box operator+ (Box b, Box c)
{
Box box = new Box();
box.length = b.length + c.length;
box.breadth = b.breadth + c.breadth;
box.height = b.height + c.height;
return 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);

// Add two object as follows:


Box3 = Box1 + Box2;

// 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:

Volume of Box1 : 210


Volume of Box2 : 1560
Volume of Box3 : 5400
Overloadable and Non-Overloadable Operators

The following table describes the overload ability of the operators in C#:

Operators Description

+, -, !, ~, ++, -- These unary operators take one operand and can be overloaded.

+, -, *, /, % These binary operators take one operand and can be overloaded.

==, !=, <, >, <=, >= The comparison operators can be overloaded

&&, || The conditional logical operators cannot be overloaded directly.

+=, -=, *=, /=, %= The assignment operators cannot be overloaded.

=, ., ?:, ->, new, is, sizeof,


These operators cannot be overloaded.
typeof

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

public double getVolume()


{
return length * breadth * height;
}
public void setLength( double len )
{
length = len;
}

public void setBreadth( double bre )


{
breadth = bre;
}

public void setHeight( double hei )


{
height = hei;
}
// Overload + operator to add two Box objects.
public static Box operator+ (Box b, Box c)
{
Box box = new Box();
box.length = b.length + c.length;
box.breadth = b.breadth + c.breadth;
box.height = b.height + c.height;
return box;
}

public static bool operator == (Box lhs, Box rhs)


{
bool status = false;
if (lhs.length == rhs.length && lhs.height == rhs.height
&& lhs.breadth == rhs.breadth)
{
status = true;
}
return status;
}
public static bool operator !=(Box lhs, Box rhs)
{
bool status = false;
if (lhs.length != rhs.length || lhs.height != rhs.height
|| lhs.breadth != rhs.breadth)
{
status = true;
}
return status;
}
public static bool operator <(Box lhs, Box rhs)
{
bool status = false;
if (lhs.length < rhs.length && lhs.height
< rhs.height && lhs.breadth < rhs.breadth)
{
status = true;
}
return status;
}

public static bool operator >(Box lhs, Box rhs)


{
bool status = false;
if (lhs.length > rhs.length && lhs.height
> rhs.height && lhs.breadth > rhs.breadth)
{
status = true;
}
return status;
}
public static bool operator <=(Box lhs, Box rhs)
{
bool status = false;
if (lhs.length <= rhs.length && lhs.height
<= rhs.height && lhs.breadth <= rhs.breadth)
{
status = true;
}
return status;
}

public static bool operator >=(Box lhs, Box rhs)


{
bool status = false;
if (lhs.length >= rhs.length && lhs.height
>= rhs.height && lhs.breadth >= rhs.breadth)
{
status = true;
}
return status;
}
public override string ToString()
{
return String.Format("({0}, {1}, {2})", length, breadth, height);
}

}
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);

//displaying the Boxes using the overloaded ToString():


Console.WriteLine("Box 1: {0}", Box1.ToString());
Console.WriteLine("Box 2: {0}", Box2.ToString());

// 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);

// Add two object as follows:


Box3 = Box1 + Box2;
Console.WriteLine("Box 3: {0}", Box3.ToString());
// volume of box 3
volume = Box3.getVolume();
Console.WriteLine("Volume of Box3 : {0}", volume);

//comparing the boxes


if (Box1 > Box2)
Console.WriteLine("Box1 is greater than Box2");
else
Console.WriteLine("Box1 is greater than Box2");
if (Box1 < Box2)
Console.WriteLine("Box1 is less than Box2");
else
Console.WriteLine("Box1 is not less than Box2");
if (Box1 >= Box2)
Console.WriteLine("Box1 is greater or equal to Box2");
else
Console.WriteLine("Box1 is not greater or equal to Box2");
if (Box1 <= Box2)
Console.WriteLine("Box1 is less or equal to Box2");
else
Console.WriteLine("Box1 is not less or equal to Box2");
if (Box1 != Box2)
Console.WriteLine("Box1 is not equal to Box2");
else
Console.WriteLine("Box1 is not greater or equal to Box2");
Box4 = Box3;
if (Box3 == Box4)
Console.WriteLine("Box3 is equal to Box4");
else
Console.WriteLine("Box3 is not equal to Box4");

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");

Console.WriteLine("Main Method Employee Code & Name : {0} , {1} \n",


4
objEmp.EmployeeCode, objEmp.EmployeeName);

5 PassReferenceByRefernce(ref objEmp);

Console.WriteLine("Main Method Employee Code & Name After PassReferenceByRefernce :


6
{0} , {1} \n", objEmp.EmployeeCode, objEmp.EmployeeName);

7 }
Display output for above result as follows.

1 Main Method Output Before PassReferenceByRefernce // 9 , Questpond ;

2 PassReferenceByRefernce Output // 7 , Questpond Added RefernceByRef;

3 After the PassReferenceByRefernce // 7 , Questpond Added RefernceByRef;

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.

Repeat the same process using 'out' keyword.

What are generic collections in C# using an example?


Generic Collections
In our previous article we saw on generics and how we separated the data-type logic from a logical code snippet using generics. Taking forward
that same logic, means separating collection logic i.e (Add, Search, Remove, Clear) from data-type, we will see different types of generic
collections available in .net.

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.

Why Generic Collections

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.

Development team applied generic concept on dotnet collections

 .NET collections to make generic collections.


 Arraylist to make list generic collections.
 Hashtables to make Dictionary.
 Stacks and Queues to make Stacks and Queues generics.

All these above collections available in "using System.Collections.Generic" namespace.

Types of Generic Collections


Generic List Collection

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

1 List obj = new List();

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 {

10 static void Main(string[] args)

11 {

12

13 List list = new List();

14
15 list.Add(1);

16 list.Add(2);

17 list.Add(9);

18

19 foreach (int numbers in list)

20 {

21 Console.WriteLine(numbers);

22 }

23

24 Console.WriteLine("Count -> {0}",list.Count);

25 Console.WriteLine("\n-------------------------------------------\n");

26

27 List list1 = new List();

28

29 list1.Add(false);

30 list1.Add(true);

31 list1.Add(true);

32 list1.Add(false);

33

34 foreach (bool booleans in list1)

35 {

36 Console.WriteLine(booleans);

37 }

38

39 Console.WriteLine("Count -> {0}", list1.Count);

40 Console.WriteLine("\n-------------------------------------------\n");

41

42 List list2 = new List();

43

44 list2.Add("Khadak");
45 list2.Add("Shiv");

46 list2.Add("Shaam");

47 list2.Add("Pradeep Dhuri");

48

49 foreach (string stringnames in list2)

50 {

51 Console.WriteLine(stringnames);

52 }

53

54 Console.WriteLine("Count -> {0}", list2.Count);

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

1 Dictionary obj = new List();

Dictionary Represents a collection of keys and values.

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 {

10 static void Main(string[] args)

11 {

12

13

14 Dictionary animaldictionary = new Dictionary();

15 animaldictionary.Add("Tiger", 3);

16 animaldictionary.Add("Lion", 2);

17 animaldictionary.Add("Panda", 1);

18

19

20 foreach (KeyValuePair pair in animaldictionary)

21 {

22 Console.WriteLine("{0}, {1}", pair.Key, pair.Value);


23 }

24

25 Console.WriteLine("\n-------------------------------------------\n");

26

27 foreach (var pair in animaldictionary)

28 {

29 Console.WriteLine("{0}, {1}", pair.Key, pair.Value);

30 }

31

32

33

34

35 }

36 }

37 }

Output

Generic Stack and Queue

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

1 Stack objstack = new Stack();

2 Queue objqueue = new Queue ();

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 {

10 static void Main(string[] args)

11 {

12

13 //Declaring Stack

14 Stack stacknum = new Stack();

15 stacknum.Push(1);

16 stacknum.Push(2);

17 stacknum.Push(3);

18 stacknum.Push(5);

19 stacknum.Push(6);

20

21

22

23 foreach (int numbers in stacknum)

24 {

25 Console.WriteLine("Stack Numbers {0}", numbers);

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

34 Stack stacknames = new Stack();

35 stacknames.Push("Pradeep Dhuri");

36 stacknames.Push("Shiv Prasad");

37 stacknames.Push("Khadak");

38 stacknames.Push("Shaam");
39

40

41 foreach (string strnames in stacknames)

42 {

43 Console.WriteLine("Stack Names {0}", strnames);

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

52 Queue Queuenum = new Queue();

53 Queuenum.Enqueue(1);

54 Queuenum.Enqueue(2);

55 Queuenum.Enqueue(3);

56 Queuenum.Enqueue(5);

57 Queuenum.Enqueue(6);

58

59

60

61 foreach (int numbers in Queuenum)

62 {

63 Console.WriteLine("Queue Numbers {0}", numbers);

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

73 Queue Queuenames = new Queue();

74 Queuenames.Enqueue("Mohan Aiyer");

75 Queuenames.Enqueue("Shiv Prasad");

76 Queuenames.Enqueue("Khadak");

77 Queuenames.Enqueue("Shaam");

78

79

80 foreach (string strnames in Queuenames)

81 {

82 Console.WriteLine("Queue Names {0}", strnames);

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 }

What are Generics

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 are strongly type collections.

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;".

Micorsoft applied generic concept on

 .NET collections to make generic collections.


 Arraylist to make list generic collections.
 Hashtables to make Dictionary.
 Stacks and Queues to make Stacks and Queues generics.

Syntax

1 public class GenericsClass

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

04 public class GenericsClass

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

15 public bool CompareResult()

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 {

32 static void Main(string[] args)

33 {

34

35 GenericsClass obj1 = new GenericsClass("Khadak", "Khadak");

36 Console.WriteLine("Compare Result obj1 --> {0}", obj1.CompareResult());

37

38 GenericsClass obj2 = new GenericsClass("Khadak", "Shaam");

39 Console.WriteLine("Compare Result obj2 --> {0}", obj2.CompareResult());

40
41

42 GenericsClass objInt1 = new GenericsClass(1, 1);

Console.WriteLine("Compare Result objInt1 --> {0}",


43
objInt1.CompareResult());

44

45 GenericsClass objInt2 = new GenericsClass(1, 8);

Console.WriteLine("Compare Result objInt2 --> {0}",


46
objInt2.CompareResult());

47

48

49 GenericsClass objChar1 = new GenericsClass((char)(97), (char)(97));

Console.WriteLine("Compare Result objChar1 --> {0}",


50
objChar1.CompareResult());

51

52

53 GenericsClass objChar2 = new GenericsClass((char)(97), (char)(98));

Console.WriteLine("Compare Result objChar2 --> {0}",


54
objChar2.CompareResult());

55

56 GenericsClass objDouble1 = new GenericsClass(1.1, 1.1);

Console.WriteLine("Compare Result objDouble1 --> {0}",


57
objDouble1.CompareResult());

58

59

60 GenericsClass objDouble2 = new GenericsClass(1.1, 1.2);

Console.WriteLine("Compare Result objDouble2 --> {0}",


61
objDouble2.CompareResult());

62

63 }

64 }

About The Code

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.

Kindly note "T" in "GenericsClass" is a generic parameter.

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.

Is C# is Modern, Type Safe, Versionable and Inter


operability Language ?
C# is a modern language

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.

It is derived from C++ and Java.


C# is Type Safe Language

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

1 string Name = 1; //cause an error

2 int a = "Hello World"; // cause an error

3 double db = a; //cause an error

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.

Why Type-Safety is Important?

Type safe code can access only the memory locations that it has permission to execute.

Type-safety is important for assembly isolation and security enforcement.

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.

How Type Safety Ensured

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# is an Inter operability Language

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

We will create a Console Application language as visual c#.

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

2 Public Class ClsVBNET

3 Dim i As Integer

4 Public Function Add(ByVal z As Integer, ByVal k As Integer) 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

02 using clsVBNET; // this is namespace

03

04

05 static void Main(string[] args){

06 int answer = 0;

07 ClsVBNET objvbnet = new ClsVBNET();

08 answer = objvbnet.Add(5,4);

09 Console.WriteLine("Add method Output is {0}",answer);

10 }
Step 5
Displaying Output i.e. 5 + 4 = 9

C# Versionable

.NET framework handles the versioning.

Since C# code which runs on .NET framework so it is a versioning language.

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:

Converting a value type to reference type is called Boxing.

About UnBoxing:

Converting a reference type to value type is called 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.

Simple Example of Boxing


1 class Program

2 {

3 static void Main(string[] args)

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.

Simple Example of UnBoxing


1 class Program

2 {

3 static void Main(string[] args)

4 {
5 int A = 5;

6 object B = A;//Boxing

7 int C = (int)B;// Unboxing

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.

Please use Visual Studio Command Prompt to launch ILDASM tool

Command: ILDASM and Press Enter Key

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:

4 //your code here

5 break;//Jump Statement

6 default:

7 //your code here

8 break;

9 }

For Example

1 switch (condition){

2 case "Add":

3 int add = num1 + num2;

4 break;//Jump Statement

5 default:

6 int add = 0;

7 break;

8 }

Expression: An integral or string type expression.

Jump-statement or break: It transfers control out of the case body.

Body of the case statement will execute only if Boolean condition matches to the case expression (If True).

Switch statement can have any number of case instances in it.


One case instance label or expression has different from another case instance label or expression.

Switch Case using an example

Now let's demonstrate a simple example using switch statement.

We are going to demonstrate simple mathematical calculation using a Console Application.

First Step is to Create Console Application :

01 using System;

02 using System.Collections.Generic;

03 using System.Linq;

04 using System.Text;

05 namespace Practical2b

06 {

07 class Program

08 {

09 static void Main(string[] args)

10 {

11 ……///code snippet

12 }

13 }

14 }

Second Step to take Input value

In this step we will ask input value from an user to execute (Add or Subtract or Multiplication or Division).

1 static void Main(string[] args){

2 Console.WriteLine("Enter a type like Add , Sub , Mul, Div");

3 string condition = Console.ReadLine();

4 }

Third Step to take Two Numbers as Input

1 static void Main(string[] args)


2 {

3 Console.WriteLine("Enter a first number");

4 int num1 = Convert.ToInt16(Console.ReadLine());

6 Console.WriteLine("Enter a second number");

7 int num2 = Convert.ToInt16(Console.ReadLine());

8 }

Fourth Step is to Create Switch Statement.

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).

01 static void Main(string[] args)

02 {

03 Console.WriteLine("Enter a first number");

04 int num1 = Convert.ToInt16(Console.ReadLine());

05

06 Console.WriteLine("Enter a second number");

07 int num2 = Convert.ToInt16(Console.ReadLine());

08

09 switch (condition){

10

11 case "Add":

12 Console.WriteLine("Added number, {0}", num1 + num2);

13 break;

14 case "Sub":
15 Console.WriteLine("Substract number, {0}", num1 - num2);

16 break;

17 case "Mul":

18 Console.WriteLine("Multiply number, {0}", num1 * num2);

19 break;

20 case "Div":

21 Console.WriteLine("Divide number, {0}", num1 / num2);

22 break;

23 default:

24 Console.WriteLine("Display number, {0} , {1} ", num1 , num2);

25 break;

26

27 }

28 }

Fifth Step Display Output

Press Ctrl + F5 to run your console application.

What is an Indexer? Explain how it is different from


property in terms of implementation.
About an Indexer

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{

3 ..code goes here

4 }

5 Set{

6 ..code goes here

7 }

8 }

So this is about an indexer. Now let go and see how an indexer is different from a property.

Difference Between Indexer and Property

1st Difference

Indexers are created by using "this" keyword and identified by its signature.

Properties don't use "this" keyword and identified by simple names.

For example

1 public string this[int parameter]{

2 Get{

3 ..code goes here

4 }

5 Set{

6 ..code goes here

7 }

8 }

Above snippet shows an indexer code with "string" as return type and followed by "this" keyword and "int" as input parameters.

1 public string EmployeeName{

2 Get{

3 ..code goes here

4 }
5 Set{

6 ..code goes here

7 }

8 }

Above snippet shows a property code with "string" as return type and followed by property name "EmployeeName".

2nd Difference

Indexers are accessed using indexes.

Properties are accessed by their names.

Indexer example

01 class clsEmployee{

02 private string[] emplcodes = new string[10];

03 public string this[int code]

04 {

05 get{

06 return emplcodes[code];

07 }

08 set{

09 emplcodes[code] = value;

10 }

11 }

12 }

13 class Program{

14 static void Main(string[] args){

15

16 clsEmployee empl = new clsEmployee();

17 empl[0] = "Shiv with Employee code";

18 empl[1] = "Khadak with Employee code";

19 empl[2] = "Shaam with Employee code";


20 }

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{

02 private string _emplname=””;

03 public string EmployeeName

04 {

05 get{

06 return _emplname;

07 }

08 set{

09 _emplnam = value;

10 }

11 }

12 }

13 class Program{

14

15 static void Main(string[] args){

16

17 clsEmployee empl = new clsEmployee();

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.

About Checked and Unchecked operator

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.

Syntax of Checked Operator

1 static void Main(string[] args){

3 checked{

4 //Block of code or expression

5 int x = 1000000 * 2000000;

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).

Syntax of UnChecked Operator

1 static void Main(string[] args){

3 unchecked{

4 //Block of code or expression


5 int x = 1000000 * 2000000;

6 }

8 }

Demonstrate Checked and Unchecked operators using an example

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.

Step 1: Create Console Application

1 class Program

2 {

3 static void Main(string[] args)

4 {

6 }

7 }

Step 2: Use int (Int32) variable to check for overflow.

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 {

3 static void Main(string[] args)

4 {

5 int inttestVariable = 2147483647;

6 Console.WriteLine("Our current int value is... " + inttestVariable);

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.

As we have shown in below code.

1 class Program

2 {

3 static void Main(string[] args)

4 {

Console.WriteLine("{0}: bytes: {1}, range: [{2},{3}]",


5
typeof(int).ToString(), sizeof(int), int.MinValue, int.MaxValue);

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 {

03 static void Main(string[] args)

04 {

05 int inttestVariable = 2147483647;

06 Console.WriteLine("Our current int value is... " + inttestVariable);

07

08 checked{

09

10 Console.WriteLine("\n");

11 inttestVariable++;

12 Console.WriteLine("Checked Value becomes... " + 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

For Unchecked operator

Now let's change the operator replacing checked with unchecked and check the output.

01 class Program

02 {

03 static void Main(string[] args)

04 {

05 int inttestVariable = 2147483647;

06 Console.WriteLine("Our current int value is... " + inttestVariable);

07

08 unchecked{

09

10 Console.WriteLine("\n");

11 inttestVariable++;

12 Console.WriteLine("Checked Value becomes... " + 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.

What are structures? Differentiate between structures


and classes
What are structures?

Structures are value types.


They get allocated on stack.
They are group of logically related data item.
They do not follow or implement object orient concepts.
All value types such as int, bool and char are structs.
The structure in C# can contain fields, methods, constants, constructors, properties, indexers, operators and even other structure
types.

Structures are useful in

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 }

Syntax of a structure starts with "struct" keyword followed by structure name

For Example

1 struct MalingList

2 {

3 private string _name;

4 private int _doornumber;

5 private string _street;

6 private string _city;

7 private string _pincode;


8 }

So this is all about structures in c-sharp. Now let's go and understand about classes.

What is a Class?

In OOPs concept Class is a general thing.


Class is nothing but a blue print or template.
Classes are reference types and they get allocated on heap.

Syntax

1 class className{

2 ……Code

3 }

Syntax of a class starts with "class" keyword followed by classname

For Example

1 class MalingList

2 {

3 private string _name;

4 private int _doornumber;

5 private string _street;

6 private string _city;

7 private string _pincode;

8 }

For Your References

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

Structures are value types.


Classes are reference types.

2nd Difference

Since structures are value types so they get allocated on stack.


Since classes are reference types so they allocated on heap.

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.

Checking Memory Usage on Stack and Heap

Now let's demonstrate structures and classes by checking the memory consumption of classes and structures on stack and heap.

For this example I will be using a Windows form application

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.

01 public struct strGraph{

02

03 private int _x;

04 private int _y;

05 public int X{

06 get { return _x; }

07 set { _x = value; }
08 }

09 public int Y{

10 get { return _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.

01 public struct clsGraph{

02

03 private int _x;

04 private int _y;

05 public int X{

06 get { return _x; }

07 set { _x = value; }

08 }

09 public int Y{

10 get { return _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.

1 private void button1_Click(object sender, EventArgs e){


2

3 for (int i = 0; i <= 100 * 1000; i++){

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

1 private void button1_Click(object sender, EventArgs e){

3 for (int i = 0; i <= 100 * 1000; i++){

4 strGraph obj = new strGraph();

5 }

7 }

Next step run the CLR profiler

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.

1 private void button1_Click(object sender, EventArgs e){

3 for (int i = 0; i <= 100 * 1000; i++){

4 clsGraph obj = new clsGraph();

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.

From this above example it is confirmed that.

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.

Understanding the concept of pass by value and pass by


reference with an example?
Before we try to understand the concept of passing parameters let’s just first understand about value types and reference types
because passing parameters is all about how to pass a value type and to pass a reference type.

What are Value Types?

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.

A value type inside a class scope also known as reference type.

Reference type Memory is allocated in heap.

Example 1

1 string[] str = new string[2] {"ABC","PQR"};

2 class obj = new class();

Example 2

1 class Employee

2 {

3 Private int empCode = 4545;

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.

What are Passing Parameters?

Passing the parameters is of two types

Pass by Value Type


Pass by Reference Type

Passing the value type or reference type can be done through using methods, properties, constructors and indexers.

Pass By Value Type

Pass by value assumes that the variable value is set before the method or function is called.

We can pass the value type in two ways

Pass value types by value


Pass value type by reference

Pass by Reference Type

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.

We can pass the reference type in two ways

Pass reference types by value


Pass reference type by reference

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.

Understanding Pass By Value Type

We can pass the value type in two ways

Pass value types by value


Pass value type by reference

Pass value types by value

To a method or a function we need to pass value type as value

For Example:

1 public static void PassValueByValue(int val)

2 {

3 val *= val;

4 Console.WriteLine("Output : PassValueByValue : {0}", 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.

1 static void Main(string[] args)

2 {

3 int testval = 5;

4 Console.WriteLine("Main method value : {0} \n", testval);


5 PassValueByValue(testval);

6 Console.WriteLine("Main method value After PassValueByValue : {0} \n", testval);

7 }

Display output for above result as follows.

1 Output // 5 ;

2 PassValueByValue // 25;

3 After the PassValueByValue // 5;

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.

Pass value types by reference

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:

1 public static void PassValueByReferenceByRef(ref int val)

2 {

3 val = val + 55;

4 Console.WriteLine("Output : PassValueByReference : {0}", val);

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.

1 static void Main(string[] args)

2 {

3 int testval = 5;

4 Console.WriteLine("Main method value : {0} \n", testval);

5 PassValueByReferenceByRef(ref testval);

6 Console.WriteLine("Main method value After PassValueByReference : {0} \n",


testval);

7 }

Display output for above result as follows.

1 Output // 5 ;

2 PassValueByReferenceByRef // 60;

3 After the PassValueByReference // 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.

Understanding Pass by Reference Type

We can pass the reference type in two ways

 Pass reference types by value


 Pass reference type by reference

Pass reference types by value

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.

01 public class Employee{

02

03 public string EmployeeName{ set; get; }

04 public int EmployeeCode { set; get; }

05 public Employee(int emplcode, string emplname)

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.

1 static void Main(string[] args)

2 {

3 Employee objEmp = new Employee(009, "Questpond");

Console.WriteLine("Main Method Employee Code & Name : {0} , {1} \n",


4
objEmp.EmployeeCode, objEmp.EmployeeName);

5 }

To a method or a function we need to pass reference type as value

For Example:

1 public static void PassReferenceByValue(Employee emp)

2 {

3 emp.EmployeeName = "Questpond Added Value";

4 emp.EmployeeCode = 8;

Console.WriteLine("PassReferenceByValue Employee Code & Name : {0} , {1} \n",


5
emp.EmployeeCode, emp.EmployeeName);

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.

1 static void Main(string[] args)

2 {

3 Employee objEmp = new Employee(009, "Questpond");

Console.WriteLine("Main Method Employee Code & Name : {0} , {1} \n",


4
objEmp.EmployeeCode, objEmp.EmployeeName);

5 PassReferenceByValue(objEmp);

Console.WriteLine("Main Method Employee Code & Name After PassReferenceByValue : {0}


6
, {1} \n", objEmp.EmployeeCode, objEmp.EmployeeName);
7 }

Display output for above result as follows.

1 Main Method Output Before PassReferenceByValue // 9 , Questpond ;

2 PassReferenceByValue Output // 8 , Questpond Added Value;

3 After the PassReferenceByValue // 8 , Questpond Added Value;

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.

Pass reference type by reference

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.

1 static void Main(string[] args)

2 {

3 Employee objEmp = new Employee(009, "Questpond");

Console.WriteLine("Main Method Employee Code & Name : {0} , {1} \n",


4
objEmp.EmployeeCode, objEmp.EmployeeName);

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:

1 public static void PassReferenceByRefernce(ref Employee emp)

2 {

3 emp.EmployeeName = "Questpond Added RefernceByRef";

4 emp.EmployeeCode = 7;

Console.WriteLine("PassReferenceByRefernce Employee Code & Name : {0} , {1} \n",


5
emp.EmployeeCode, emp.EmployeeName);

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.

1 static void Main(string[] args)

2 {

3 Employee objEmp = new Employee(009, "Questpond");

Console.WriteLine("Main Method Employee Code & Name : {0} , {1} \n",


4
objEmp.EmployeeCode, objEmp.EmployeeName);

5 PassReferenceByRefernce(ref objEmp);

Console.WriteLine("Main Method Employee Code & Name After PassReferenceByRefernce :


6
{0} , {1} \n", objEmp.EmployeeCode, objEmp.EmployeeName);

7 }

Display output for above result as follows.

1 Main Method Output Before PassReferenceByRefernce // 9 , Questpond ;

2 PassReferenceByRefernce Output // 7 , Questpond Added RefernceByRef;

3 After the PassReferenceByRefernce // 7 , Questpond Added RefernceByRef;

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.

Repeat the same process using 'out' keyword.

Sealed Classes in C# with an example and explanation


About Sealed Modifier ?

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.

Why Sealed Modifier ?

We use sealed modifiers in our programs because:

Sealed Modifier prevents a class from being inherited.

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 {

3 Public sealed void Display() { } /// Sealed Method

4 }

Example of Sealed Modifier:


1 sealed class Employee

2 {

3 public void DisplayEmployeeDetails(){

4 Console.WriteLine("Employee Name --> Questpond and Employee Code --> 009");

5 }

6 }

In above the code we have class "Employee"with "sealed" type modifier and simple "DisplayEmployeeDetails" method which
displays employee details.

Now let's perform test on sealed type modifier.

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.

Conclusion: Sealed member prevent the class for further inheriting.

What is a constructor in c# and list types of constructors


in C#?
What is a constructor?

Constructor is a method which gets executed automatically when we create or instantiate object of that class having constructor.

More Highlights of 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 can either be static constructor or an instance constructor.

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(){

4 //Code goes here

5 }

6 }

Types of Constructors in C#

There are 5 types of constructor in C# as listed below

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.

Example of Default Constructor

01 public class clsAddition{

02

03 public int Mycode = 0;

04 public clsAddition(){

05 Mycode = 9;

06 }

07 }

08

09 class Program{
10

11 static void Main(string[] args){

12 clsAddition obj = new clsAddition();

13 Consolw.WriteLine("Code value is : {0}",obj.Mycode);

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.

Example of Parameterized Constructor

01 public class clsAddition{

02

03 public string itype = "";

04 public int x = 0;

05 public int y = 0;

06 public clsAddition(string type, int a, int b){

07 itype = type;

08 x = a;

09 y = b;

10 }

11 }

12

13 class Program{

14

15 static void Main(string[] args){

16 clsAddition obj = new clsAddition("Addition",7,2);


17 Consolw.WriteLine("Type is : {0}",obj.itype);

18 Consolw.WriteLine("Variable 1 value is : {0}",obj.x);

19 Consolw.WriteLine("Variable 2 value is : {0}",obj.y);

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.

Example of Copy Constructor

01 class Car

02 {

03 public string _nameofcar = "";

04 public int _carno = 0;

05 public double _carprice = 0;

06

07 public Car(string NameofCar, int CarNumber, double CarPrice)

08 {

09 _nameofcar = NameofCar;

10 _carno = CarNumber;

11 _carprice = CarPrice;

12 }

13

14 //Copy Constructor

15 public Car(Car objCar)


16 {

17 _nameofcar = objCar._nameofcar;

18 _carno = objCar._carno;

19 _carprice = objCar._carprice;

20 }

21

22

23 }

24

25 class Program

26 {

27 static void Main(string[] args)

28 {

29 Car obj1 = new Car("BMW Sedan", 4545, 5000000);

30 Car obj2 = new Car(obj1);

31 Console.WriteLine("Car Name : {0}", obj2._nameofcar);

32 Console.WriteLine("Car Number : {0}", obj2._carno);

33 Console.WriteLine("Car Price : {0}", obj2._carprice);

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

Static constructor is created using a static keyword as shown below.

1 class clsAddition{
2

3 static clsAddition(){

4 ….Code goes here

5 }

6 }

Example of Static Constructor

01 public class clsAddition

02 {

03

04 private int a = 0;

05 private int b = 0;

06 public static int _counter;

07

08 public clsAddition(int x, int y)

09 {

10 a = x;

11 b = y;

12 }

13

14 static clsAddition()

15 {

16 Console.WriteLine("Static constructor is called");

17 _counter++;

18 Console.WriteLine("Counter Value is {0}", _counter);

19 }

20

21 public clsAddition()

22 {
23 a = 150;

24 b = 160;

25 }

26

27

28 public void Display()

29 {

30 Console.WriteLine("Addition Value is {0}", a + b);

31 }

32

33

34 }

35

36

37 class Program

38 {

39 static void Main(string[] args)

40 {

41

42 clsAddition objadd = new clsAddition();

43 clsAddition._counter = 9;

44 objadd.Display();

45

46 Console.WriteLine("\nSecond time calling a constructor \n");

47

48 objadd = new clsAddition(10, 15);

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.

See the output

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

A constructor with "private" access modifier in a class is called as private constructor.

A class with private constructor cannot be inherited.

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.

01 public class clsEmployee

02 {

03

04 public static int emplcounter = 9;

05 private clsEmployee()
06 {

07

08 }

09

10

11 }

12

13 class Program

14 {

15 static void Main(string[] args)

16 {

17

18 Console.WriteLine("Counter value" + clsEmployee.emplcounter);

19

20 }

21 }

Implementing Interface in C# with an example


What is an Interface?

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.

We declare interface by using "interface" keyword.

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.

1 class clsEmployee : IEmployee

2 {

3 public void DisplayEmployeeDetails(){

4 Console.WriteLine(“Displaying employee details…”);

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.

Benefits of using an 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.

We can use the "interface" as a pointer in the different layers of applications.

We can use an interface for implementing run time polymorphism.

Various Forms of implementing interface

There are two of ways of implementing interfaces

Explicit
Implicit

Explicit interface implementation

To implement an interface explicitly we have to define an interface name followed by (".") dot operator then the method name.

Sample as shown in below snipped code.

1 public class Employee : IEmployee

2 {

3 void IEmployee.DisplayEmployeeDetails()
4 {

Console.WriteLine("IEmployee Employee Name --> Questpond and Employee


5
Code --> 009");

6 }

7 }

When you put a dot operator after an interface name you will see all the signatures defined in an interface.

In which scenario we use explicit interface implementation

When we have two different interfaces with same method name then in that scenario we can use explicit interface
implementation.

Example of Explicit Interface

1 public interface IEmployee{

2 void DisplayEmployeeDetails();

3 }

5 public interface ICompany{

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.

1 public class clsEmployee : IEmployee,ICompany

2 {

4 //class code goes here


5

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.

1 public class Employee : IEmployee,ICompany

2 {

3 void ICompany.DisplayEmployeeDetails(){

Console.WriteLine("ICompany Employee Name --> Questpond and Employee


4
Code --> 009");

5 }

6 void IEmployee.DisplayEmployeeDetails(){

Console.WriteLine("IEmployee Employee Name --> Questpond and Employee


7
Code --> 009");

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

03 static void Main(string[] args)

04 {

05 IEmployee IEmp = new clsEmployee();

06 IEmp.DisplayEmployeeDetails();

07

08 ICompany IComp = new clsEmployee();

09 IComp.DisplayEmployeeDetails();

10 }
11

12 }

Let's run the application (Ctrl + F5) and display the output as shown it below.

Implicit interface implementation

To implement an interface implicitly we have to implement the interface name before the class using colon ":" operator as shown
in below snipped code.

1 public class Employee : IEmployee

2 {

3 public void DisplayEmployeeDetails()

4 {

Console.WriteLine("Employee Name --> Questpond and Employee Code -->


5
009");

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.

1 public class Employee : IEmployee

2 {

3 public void DisplayEmployeeDetails()

4 {

Console.WriteLine("Employee Name --> Questpond and Employee Code -->


5
009");

6 }

7 }

Console Application

Finally let's create the objects of an interface "IEmployee" in our main method of a Console Application program.

1 public class Program{

3 static void Main(string[] args)

4 {

5 IEmployee IEmp = new clsEmployee();


6 IEmp.DisplayEmployeeDetails();

7 }

9 }

Let's run the application (Ctrl + F5) and display the output as shown it below.

OOPS Principle - Polymorphism in C# with an example


What is Polymorphism

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.

What are types of Polymorphism

There are basically two types of polymorphism in c# i.e.

Static Polymorphism
Dynamic Polymorphism

Static Polymorphism

Static polymorphism is also called as Compile Time polymorphism. In Static polymorphism


methods are overloaded with same name but having different signatures.So it is called as
method overloading.

Example of Static Polymorphism


01 public class clsCalculation

02 {
03

04 public int Add(int a, int b)

05 {

06 return a + b;

07 }

08

09 public double Add(int z, int x, int c)

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.

Example of Dynamic Polymorphism


01 public class clsShape
02 {

03 public int _radius = 5;

04

05 public virtual double getArea()

06 {

07 return 0;

08 }

09

10 }

11

12 public class clsCircle : clsShape

13 {

14

15 public override double getArea()

16 {

17 return 3.14 * _radius * _radius;

18 }

19

20 }

21

22 public class clsSphere : clsShape

23 {

24

25 public override double getArea()

26 {

27 return 4 * 3.14 * _radius * _radius;

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.

Click here to know more How to Implement Inheritance in C#.

So that you have understood about Polymorphism, Static Polymorphism and Dynamic
Polymorphism. Now let's see a simple example of polymorphism.

Simple example of polymorphism using c sharp

In this example we will illustrate an example of dynamic polymorphism.we will take up above
the example and try to implement it.

01 public class clsShape

02 {

03 public int _radius = 5;

04

05 public virtual double getArea()

06 {

07 return 0;

08 }

09

10 }

11

12 public class clsCircle : clsShape

13 {

14

15 public override double getArea()


16 {

17 return 3.14 * _radius * _radius;

18 }

19

20 }

21

22 public class clsSphere : clsShape

23 {

24

25 public override double getArea()

26 {

27 return 4 * 3.14 * _radius * _radius;

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.

Step 1 - Creating Console Application

1 class Program

2{

3 static void Main(string[] args)

4 {

6 //code goes here

7 }
8}

Step 2 - Creating Base Class Object

In this step we will create base class object and assign it to derived classes.

01 class Program

02 {

03 static void Main(string[] args)

04 {

05

06 clsShape objShape1 = new clsCircle();

07 clsShape objShape2 = new clsSphere();

08

09 }

10 }

So as you see from above code that we have created two objects "objShape1" for "clsCircle"
and "objShape2" for "clsSphere" respectively.

Step 3 - Displaying the Result

01 class Program

02 {

03 static void Main(string[] args)

04 {

05

06 clsShape objShape1 = new clsCircle();

07 clsShape objShape2 = new clsSphere();

Console.WriteLine("Radius of a Cirle is - {0}",


08
objShape1.getArea());

Console.WriteLine("Radius of a Sphere is - {0}",


09
objShape2.getArea());
10

11 }

12 }

Step 4 - Output

Radius of a Cirle is - 78.5

Radius of a Sphere is - 314

OOPS Principle - Inheritance in C# with an example


Definition of Inheritance

Inheritance means parent-child relationship.By using Inheritance methodology we can create a


new class by using existing class code (i.e. reuse existing methods, properties etc).It also referred
to as reusability of the code so by using Inheritance we can reuse the code again and again.

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{

3 ...parent class code

5}

7 class ChildClass : ParentClass{

8 ...child class code

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 to Implement Interitance

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

Reusability of the code.

Types of inheritance in c#

There are 5 types of inheritance as shown below.

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

03 public void CompanyName(){

04

05 Console.WriteLine("Name of the Company");

06

07 }

08

09 public void CompanyAddress(){

10

11 Console.WriteLine("Address of the Company");

12

13 }

14

15 }

16

17 class Employee : Company {


18

19 public void NameofEmployee(){

20

21 Console.WriteLine("Name of the Employee");

22

23 }

24

25 public void Salary(){

26

27 Console.WriteLine("Salary of the Employee");

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{

3 public void HeadOfficeAddress(){

5 Console.WriteLine("Head Office Address");

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.

1 class BranchOffice : HeadOffice{

3 public void BranchOfficeAddress(){


4

5 Console.WriteLine("Branch Office Address");

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.

01 class Employee : BranchOffice {

02

03 public void NameofEmployee(){

04

05 Console.WriteLine("Name of the Employee");

06

07 }

08

09 public void Salary(){

10

11 Console.WriteLine("Salary of the Employee");

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

03 public void HeadOfficeAddress(){

04

05 Console.WriteLine("Head Office Address");

06

07 }
08 }

09

10

11 class BranchOffice1 : HeadOffice{

12

13 public void BranchOfficeAddress(){

14

15 Console.WriteLine("Branch Office Address");

16

17 }

18

19 }

20

21 class BranchOffice2 : HeadOffice{

22

23 public void BranchOfficeAddress(){

24

25 Console.WriteLine("Branch Office Address");

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.

01 //This part of code is related to hierarchical inheritance

02 class HeadOffice{

03

04 public void HeadOfficeAddress(){

05

06 Console.WriteLine("Head Office Address");

07

08 }

09 }
10

11

12 class BranchOffice1 : HeadOffice{

13

14 public void BranchOfficeAddress(){

15

16 Console.WriteLine("Branch Office Address");

17

18 }

19

20 }

21

22 class BranchOffice2 : HeadOffice{

23

24 public void BranchOfficeAddress(){

25

26 Console.WriteLine("Branch Office Address");

27

28 }

29

30 }

////This part of code is related to combination of hierarchical inheritance


01
and multi level inheritance

02

03 class Employee : BranchOffice2 {

04

05 public void NameofEmployee(){


06

07 Console.WriteLine("Name of the Employee");

08

09 }

10

11 public void Salary(){

12

13 Console.WriteLine("Salary of the Employee");

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.

Example of Inheritance using C#


01 public class Car{

02 private string rearviewmirror;

03 private string gear;

04 private string clutch;

05 private string steering;

06

07 public string RearViewMirror

08 {

09 get { return rearviewmirror; }

10 set { rearviewmirror = value; }

11 }

12
13 public string Gear

14 {

15 get { return gear; }

16 set { gear = value; }

17 }

18

19 public string Clutch

20 {

21 get { return clutch; }

22 set { clutch = value; }

23 }

24

25 public string Steering

26 {

27 get { return steering; }

28 set { steering = value; }

29 }

30

31 public virtual void CarPrice()

32 {

33 Console.WriteLine("Car Prize is : 0");

34 }

35

36 public virtual void NameofCar()

37 {

38 Console.WriteLine("Company Name of this Car is -- ");

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"

Derived Class 1 implemented with base class Car

01 public class SentroCar:Car

02 {

03

04 public override void CarPrice()

05 {

06 Console.WriteLine("Car Prize is : 2.5L INR");

07 }

08 public override void NameofCar()

09 {

10 Console.WriteLine("Company Name of this Car is Sentro");

11 }

12 }

Derived Class 2 implemented with base class Car

01 public class BCWCar : Car

02 {

03

04 public override void CarPrice()

05 {

06 Console.WriteLine("Car Prize is : 4.5L INR");


07 }

08 public override void NameofCar()

09 {

10 Console.WriteLine("Company Name of this Car is BCW ");

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.

Output by Using Console Application

01 class Program

02 {

03 static void Main(string[] args)

04 {

05

06 Car obj = new SentroCar();

07 obj.CarPrice();

08 obj.NameofCar();

09

10 Car obj = new BCWCar();

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.

_______________________________________________________________

OOPS Principle - Encapsulation in C# with an example


Encapsulation is way to hide data, properties and methods from outside the world or
outside of the class scope and exposing only necessary thing.Encapsulation complements
Abstraction. Abstraction display only important features of a class and Encapsulation hides
unwanted data or private data from outside of a class.It hides the information within the object
and prevents from accidental corruption.

How we can achieve Encapsulation

We can achieve Encapsulation by using "private" access modifier as shown in below snippet of
code.

1 class Employee{

3 private void AccountInformation(){

4 Console.WriteLine("Displaying Account Details");

5 }

7}

Why to use Encapsulation

Encapsulation means protecting important data inside the class which we do not
want to be exposed outside of the class.

Lets consider example of a Television(TV).

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.

Example of Encapsulation using Csharp


01 class clsTelevision{

02

03 private void TVmachine(){

04

05 Console.WriteLine("Machine of a Television");

06

07 }

08

09 private void TVcolortube(){

10

11 Console.WriteLine("Color Tube of a Television");

12

13 }

14

15 public void TVKeys(){

16

17 Console.WriteLine("Keys of a Television");

18

19 }

20

21 public void TVRemote(){


22

23 Console.WriteLine("Remote of a Television");

24

25 }

26

27 public void TVScreen(){

28

29 Console.WriteLine("Wide Screen of a Television");

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.

So before implementing encapsulation or abstaction think in terms of real world scenario as


needed for your application or list down things which you want hide or display in your
applications.

OOPS Principle - Abstraction in C# with an example and


explanation
Definition

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.

Necessary things means compulsary to know before starting a car

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

1. Internal Details of a Car


2. Car Engine
3. Diesal Engine
4. Exhaust System
5. Silencer

Now above same thing let me put in the coding style using C#

01 public class Car


02
03 private string _nameofcar = "My Car";
04 private string _colorofcar = "Red";

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 Class and Abstract Method With An Example


Using C#
About Abstract Class

Abstract class in csharp is defined using "abstract" keyword


An abstract class may contain abstract methods and accessors (properties).
Non abstract methods or properties should provide actual implementation in an abstract class.

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

1 abstract class absCalculator

2 ...code starts here

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.

Non Abstract Method

In an abstract class a method which doesn't have a keyword "abstract" and provide any
implementation is called non abstract method.

Why Abstract Class

Abstract class enforces derived classes to provide all implementation logic for abstract methods
or properties.

Use of an Abstract Class

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.

01 abstract class absCalculate

02

03 //A Non abstract method

04 public int Addition(int Num1, int Num2)

05

06 return Num1 + Num2;

07 }

08

09 //An abstract method, to be overridden in derived class

10 public abstract int Multiplication(int Num1, int Num2);

11 }
Now next step lets create a class "clsCalculate" and implement it with abstract class
"absCalculate".

1 class clsCalculate:absCalculate

3 ...code

4 }

And now lets build this application.

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

4 //using override keyword implementing the abstract method

5 public override int Multiplication(int Num1, int Num2)

7 return Num1 * Num2;

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

04 static void Main(string[] args)

05

06

07 Console.WriteLine("Please Enter First Number");

08 int num1 = Convert.ToInt16(Console.ReadLine());

09

10 Console.WriteLine("Please Enter Second Number");

11 int num2 = Convert.ToInt16(Console.ReadLine());

12

13 absCalculate objabCal = new clsCalculate();

14 int add = objabCal.Addition(num1, num2);

15 int multiplied = objabCal.Multiplication(num1, num2);

Console.WriteLine("Added Number is : 0}, Multiplied Number is


16
: 1}", add, multiplied);

17 }

18 }

Output

You might also like