0% found this document useful (0 votes)
444 views115 pages

C# Interview Uestions

When declaring a variable in .NET, memory is allocated on either the stack or heap depending on the variable type. Value types like int are stored on the stack, while reference types like objects are stored on the heap. The stack uses LIFO memory allocation and deallocation, while the heap relies on garbage collection. Moving data between the stack and heap, known as boxing and unboxing, can negatively impact performance.

Uploaded by

praveen kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
444 views115 pages

C# Interview Uestions

When declaring a variable in .NET, memory is allocated on either the stack or heap depending on the variable type. Value types like int are stored on the stack, while reference types like objects are stored on the heap. The stack uses LIFO memory allocation and deallocation, while the heap relies on garbage collection. Moving data between the stack and heap, known as boxing and unboxing, can negatively impact performance.

Uploaded by

praveen kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 115

What goes inside when you declare a variable?

When you declare a variable in a .NET application, it allocates some chunk of memory in the RAM.
This memory has three things: the name of the variable, the data type of the variable, and the value
of the variable.

That was a simple explanation of what happens in the memory, but depending on the data type,
your variable is allocated that type of memory. There are two types of memory allocation: stack
memory and heap memory. In the coming sections, we will try to understand these two types of
memory in more detail.

Stack and heap


In order to understand stack and heap, let’s understand what actually happens in the below code
internally.
public void Method1()
{
// Line 1
int i=4;

// Line 2
int y=2;

//Line 3
class1 cls1 = new class1();
}

It’s a three line code, let’s understand line by line how things execute internally.

 Line 1: When this line is executed, the compiler allocates a small amount of memory in the stack. The
stack is responsible for keeping track of the running memory needed in your application.
 Line 2: Now the execution moves to the next step. As the name says stack, it stacks this memory
allocation on top of the first memory allocation. You can think about stack as a series of
compartments or boxes put on top of each other.

Memory allocation and de-allocation is done using LIFO (Last In First Out) logic. In other words
memory is allocated and de-allocated at only one end of the memory, i.e., top of the stack.

 Line 3: In line 3, we have created an object. When this line is executed it creates a pointer on the
stack and the actual object is stored in a different type of memory location called ‘Heap’. ‘Heap’ does
not track running memory, it’s just a pile of objects which can be reached at any moment of time.
Heap is used for dynamic memory allocation.
 One more important point to note here is reference pointers are allocated on stack. The
statement, Class1 cls1; does not allocate memory for an instance of Class1, it only allocates a
stack variable cls1 (and sets it tonull). The time it hits the new keyword, it allocates on "heap".
Exiting the method (the fun): Now finally the execution control starts exiting the method. When it
passes the end control, it clears all the memory variables which are assigned on stack. In other words
all variables which are related to int data type are de-allocated in ‘LIFO’ fashion from the stack.

The big catch – It did not de-allocate the heap memory. This memory will be later de-allocated by
the garbage collector.

Now many of our developer friends must be wondering why two types of memory, can’t we just
allocate everything on just one memory type and we are done?

If you look closely, primitive data types are not complex, they hold single values like ‘int i = 0’.
Object data types are complex, they reference other objects or other primitive data types. In other
words, they hold reference to other multiple values and each one of them must be stored in
memory. Object types need dynamic memory while primitive ones needs static type memory. If the
requirement is of dynamic memory, it’s allocated on the heap or else it goes on a stack.

Value types and reference types


Now that we have understood the concept of Stack and Heap, it’s time to understand the concept of
value types and reference types. Value types are types which hold both data and memory on the
same location. A reference type has a pointer which points to the memory location.

Below is a simple integer data type with name i whose value is assigned to another integer data
type with namej. Both these memory values are allocated on the stack.

When we assign the int value to the other int value, it creates a completely different copy. In other
words, if you change either of them, the other does not change. These kinds of data types are called
as ‘Value types’.

When we create an object and when we assign an object to another object, they both point to the
same memory location as shown in the below code snippet. So when we assign obj to obj1, they
both point to the same memory location.

In other words if we change one of them, the other object is also affected; this is termed as
‘Reference types’.

So which data types are ref types and which are


value types?
In .NET depending on the data type, the variable is either assigned on the stack or on the heap.
‘String’ and ‘Objects’ are reference types, and any other .NET primitive data types are assigned on the
stack. The figure below explains the same in a more detail manner.

Boxing and unboxing


Wow, you have given so much knowledge, so what’s the use of it in actual programming? One of the
biggest implications is to understand the performance hit which is incurred due to data moving from
stack to heap and vice versa.

Consider the below code snippet. When we move a value type to reference type, data is moved from
the stack to the heap. When we move a reference type to a value type, the data is moved from the
heap to the stack.

This movement of data from the heap to stack and vice-versa creates a performance hit.

When the data moves from value types to reference types, it is termed ‘Boxing’ and the reverse is
termed ‘UnBoxing’.

If you compile the above code and see the same in ILDASM, you can see in the IL code how ‘boxing’
and ‘unboxing’ looks. The figure below demonstrates the same.

Performance implication of boxing and


unboxing
In order to see how the performance is impacted, we ran the below two functions 10,000 times. One
function has boxing and the other function is simple. We used a stop watch object to monitor the
time taken.

The boxing function was executed in 3542 ms while without boxing, the code was executed in 2477
ms. In other words try to avoid boxing and unboxing. In a project where you need boxing and
unboxing, use it when it’s absolutely necessary.

With this article, sample code is attached which demonstrates this performance implication.

Currently I have not included source code for unboxing but the same holds true for it. You can write
code and experiment it using the stopwatch class.
Extension methods are a new feature in C# 3.0. An extension method enables us to add methods to
existing types without creating a new derived type, recompiling, or modify the original types. We can
say that it extends the functionality of an existing type in .NET. An extension method is
a static method to the existing static class. We call an extension method in the same general
way; there is no difference in calling.

Feature and Property of Extension Methods


The following list contains basic features and properties of extension methods:

1. It is a static method.
2. It must be located in a static class.
3. It uses the "this" keyword as the first parameter with a type in .NET and this method will be called
by a given type instance on the client side.
4. It also shown by VS intellisense. When we press the dot (.) after a type instance, then it comes in VS
intellisense.
5. An extension method should be in the same namespace as it is used or you need to import the
namespace of the class by a using statement.
6. You can give any name for the class that has an extension method but the class should be static.
7. If you want to add new methods to a type and you don't have the source code for it, then the
solution is to use and implement extension methods of that type.
8. If you create extension methods that have the same signature methods as the type you are
extending, then the extension methods will never be called.

Using the Code


We create an extension method for a string type so string will be specified as a parameter for
this extension method and that method will be called by a string instance using the dot operator.

In the above method WordCount(), we are passing a string type with this so it will be called by
the stringtype variable, in other words a string instance.

Now we create a static class and two static methods, one for the total word count in
a string and another for the total number of characters in a string without a space.

Hide Copy Code


using System;
namespace ExtensionMethodsExample
{
public static class Extension
{
public static int WordCount(this string str)
{
string[] userString = str.Split(new char[] { ' ', '.', '?' },
StringSplitOptions.RemoveEmptyEntries);
int wordCount = userString.Length;
return wordCount;
}
public static int TotalCharWithoutSpace(this string str)
{
int totalCharWithoutSpace = 0;
string[] userString = str.Split(' ');
foreach (string stringValue in userString)
{
totalCharWithoutSpace += stringValue.Length;
}
return totalCharWithoutSpace;
}
}
}

Now we create an executable program that has a string as an input and uses an extension method
to count the total words in that string and the total number of characters in that string then
show the result in a console screen.

Hide Copy Code


using System;
namespace ExtensionMethodsExample
{
class Program
{
static void Main(string[] args)
{
string userSentance = string.Empty;
int totalWords = 0;
int totalCharWithoutSpace = 0;
Console.WriteLine("Enter the your sentance");
userSentance = Console.ReadLine();
//calling Extension Method WordCount
totalWords = userSentance.WordCount();
Console.WriteLine("Total number of words is :"+ totalWords);
//calling Extension Method to count character
totalCharWithoutSpace = userSentance.TotalCharWithoutSpace();
Console.WriteLine("Total number of character is :"+totalCharWithoutSpace);
Console.ReadKey();
}
}
}
Introduction
Static keyword is widely used to share the same field or method among all the objects of the class.
The actual goal of the static keyword is to share a single data over all the objects.

There are three types of sharing using the static keyword. They are:

 Static Method
 Static Field
 Static Class

Now I am going to give a short brief on these three types.

Static Method

A static method can be accessed from outside the class without creating any object of this class.
This staticmethod can be accessed directly by the name of the static method followed by the .
(dot operator) and the class name.

For example, we can consider the Sqrt method of the Math class. This is how the Sqrt method of
the real Mathclass is defined :

Hide Copy Code

class Math
{
// Do something
public static double Sqrt(double d)
{
// Do something
}
}

From the previous example, you can notify that the Sqrt method is declared as static so that it
can be accessed by using the class name directly, no object of the Math class is required to access
the static method.

So, here I will like to some general properties of a static method:

 It can access only the static fields of the class.


 It can directly invoke the methods that are defined as static.

Static Fields

A static field is shared among all the objects of the of the class. So if an object changes this value,
then all the objects of this class will get the changed value.
Look at the example below:

Hide Copy Code

class Point
{
public Point()
{
this.x = -1;
this.y = -1;
Console.WriteLine("Deafult Constructor Called");
objectCount++;
}

public Point(int x, int y)


{
this.x = x;
this.y = y;
Console.WriteLine("x = {0} , y = {1}", x, y);
objectCount++;
}

private int x, y;
public static int objectCount = 0;
}

Now if we create three objects for this class:

Hide Copy Code

Point origin1 = new Point(); // objectCount = 1


Point origin2 = new Point(); // objectCount = 2
Point origin3 = new Point(); // objectCount = 3

Here these three objects share the same field so every time the static field objectCount is
incremented.

Static Class

A static class is used to hold all the utility methods and fields. A static Class has some
properties:

 All the methods and fields inside the class must be declared as static.
 A static class cannot contain any instance method or data.
 No object can be created (even using the “new” keyword) of this class.
 It can have a default constructor and it is also static.

Example

Let us consider an example.


Point.cs

Hide Shrink Copy Code

using System;
using System.Collections.Generic;
using System.Text;

namespace ConAppCH7CCons
{
class Point
{
public Point()
{
this.x = -1;
this.y = -1;
Console.WriteLine("Deafult Constructor Called");
objectCount++;
}
public Point(int x, int y)
{
this.x = x;
this.y = y;
Console.WriteLine("x = {0} , y = {1}", x, y);
objectCount++;
}
public double DistanceTo(Point other)
{
int xDiff = this.x - other.x;
int yDiff = this.y - other.y;
return Math.Sqrt((xDiff * xDiff) + (yDiff * yDiff));
}

public static int FnObjectCount()


{
return objectCount;
}

private int x, y;
private static int objectCount = 0;
}
}

ConstructorExample.cs
Hide Copy Code

using System;
using System.Collections.Generic;
using System.Text;

namespace ConAppCH7CCons
{
class ConstructorExample
{
static void Main(string[] args)
{
Point origin = new Point();
Point bottomRight = new Point(1024, 1280);
double distance = origin.DistanceTo(bottomRight);
Console.WriteLine("distance = {0}",distance);
Console.WriteLine("No of Objects {0}", Point.FnObjectCount());
Console.ReadLine();
}
}
}

In this example, the FnObjectCount() method is called directly with the class name, no object is
required here.

If you want to access the static method with an object like:

Hide Copy Code

bottomRight.FnObjectCount() // do not write this

then the compiler will report an error.

Now, take a deeper look into the FnObjectCount() static method:

Hide Copy Code

public static int FnObjectCount()


{
return objectCount;
}

As it is a static method, it can hold only a static field or static method

Constants:

Constants are declared using a "const" keyword.

Constants should be assigned a value at the time of the variable declaration and hence are known at
compile time. Now whenever you declare a constant variable, the C# compiler substitutes its value
directly into the Intermediate Language (MSIL).

Hide Copy Code


class ConstantEx
{
public const int number =3;
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine(ConstantEx.number);
Console.ReadLine();
}
}

Now that we understand the value is directly replaced in the MSIL, any modifications you do to the
const variable would result in something similar to below

Hide Copy Code


class Program
{
static void Main(string[] args)
{
// ConstantEx.number = 15
// The above line would throw an error as it internally becomes a statement saying
3=15
// which is not valid
Console.WriteLine(ConstantEx.number);
Console.ReadLine();
}
}

Hence, constants are immutable values which are known at compile time and do not change their
values for the life of the program.

Readonly :

Readonly variables are a little different from their colleague, const.

Readonly variables are known at runtime, they can be assigned a value either at runtime or at the
time of the instance initialization. Again, lets understand through code here.

Hide Copy Code


class ReadOnlyEx
{
public readonly int number = 10;
}

class Program
{
static void Main(string[] args)
{
ReadOnlyEx readOnlyInstance = new ReadOnlyEx();
Console.WriteLine(readOnlyInstance.number);
}
}

In the above code snippet, the readonly variable is assigned a value at the time of the declaration
and is accessed using the instance of the class rather than using the class itself. Now you may have
another instance of the class, which might have the readonly number variable assigned to a different
value based on some conditions. Can I do it? Yes, because the readonly variables are known at run
time.

Let us try doing this.

Hide Copy Code


class ReadOnlyEx
{
public readonly int number = 10;
public ReadOnlyEx()
{
number =20;
}
public ReadOnlyEx(bool IsDifferentInstance)
{
number = 100;
}
}

class Program
{
static void Main(string[] args)
{

ReadOnlyEx readOnlyInstance = new ReadOnlyEx();


Console.WriteLine(readOnlyInstance.number);

ReadOnlyEx differentInstance = new ReadOnlyEx(true);


Console.WriteLine(differentInstance.number);

Console.ReadLine();
}
}

You would see different values coming out of the program's output for the two different instance of
the class.

Hence,Readonly variables are also immutable values which are known at run time and do not change
their values for the life of the program.

Now for those "Let me read this interview question" kind of guys:
Constants:

1. Constants can be assigned values only at the time of declaration

2. Constant variables have to be accessed using "Classname.VariableName"

3. Constants are known at compile time

Read Only:

1. Read only variables can be assigned values either at runtime or at the time of instance initialization
via constructor

2. Read only variables have to be accessed using the "InstanceName.VariableName"

3. Read only variables are known at run time.

Now that we understand the differences between them, one can easily determine the appropriate
keyword as per the requirement.

Introduction
There is a lot of confusion among beginners about the abstract class. Knowing its syntax is easy, but
when and why should we use an abstract class is something which has troubled most start up
developers. I will try to explain the concept with an easy to understand example. Hope this proves to
be useful!

Background
There are a lot of definitions for an abstract class, more often I find that instead of explaining the
concept, articles deal with the actual syntax of the abstract class. For example, an abstract class
cannot have a private virtual member, blah blah.

This article will try to explain the What and the When.

Understanding the Abstract Class


An abstract class is a class which cannot be instantiated, which means you cannot create an object of
an abstract class, it can only act as a base class and other classes can derive from it. So what is the
rationale behind the existence of a class if we cannot create an object of it?
Let’s take an example of a bank to explain this. Later, we will go through the code to implement it.

Suppose you go to a bank for opening an account. Let’s see below what transpires between an
applicant and a bank staff.

Bank Staff: Welcome sir.

Applicant: I want to open an account.

Bank Staff: Sure sir, what kind of account do you want to open?

Applicant: I just want to open an account.

Bank Staff: Do you want to open a Savings Account or a Current Account?

Applicant: I do not want to open any specific account, just open an account.

Bank Staff: Sir, this is not possible, we need to create a specific type of account. Unless you tell me
the type of the account, I cannot help you.

In the light of the above discussion, we come up with the below inference for our banking
application software.

 Banks have a facility to open an account


 Bank account should be of a specific type (Saving/Current)
 Bank cannot open a generic account

To explain this concept, let's create a banking application. This application is just for demonstration
purposes and should not be used as a design guide.

Using the Code


We have a BankAccount class which is an abstract class for the reason explained above.

Irrespective of the type of account, there are certain members/behaviors which are common to all
types of accounts and thus should be part of the base class, in our case the BankAccount class.

Bank Account Common Members


 Account Owner property will have the name of the account holder
 Account Number uniquely identifies a bank account
 Minimum Balance will have the minimum threshold for the account
 Maximum Deposit Amount will have the maximum amount which can be deposited in one go
 Interest Rate is required for all bank accounts
 Transaction Summary records all the transactions taking place in an account
Bank Account Common Behavior
 You can deposit money in it.
 You can withdraw money from it.
 There should be facility to calculate interest.
 User can generate Report/ Summary to see the transactions.

Deposit and Withdraw: These are two abstract methods. It looks like Deposit/Withdraw
functionality should be the same for a SavingAccount and CurrentAccount but might not always
be as in our case. These methods are abstract because we want that the child class should give its
own implementation. (These two methods however can also be cr

eated as virtual methods but for the sake of our demonstration, let them be abstract methods.)

The CalculateInterest() method is implemented in the abstract class and the child class will
reuse this functionality, clearly an advantage of an abstract class over an interface regarding code
reuse:

Hide Shrink Copy Code

public abstract class BankAccount


{
// Name of the Account Owner, Its common for all derived classes
public string AccountOwnerName { get; set; }

// Account Number field is a common field for all the account types
public string AccountNumber { get; set; }

// A field to hold the Account Balance


public decimal AccountBalance { get; protected set; }

// A field to hold the MinimumAccount Balance


protected decimal MinAccountBalance { get; set; }

// A field to hold the Max Deposit Amount Balance


protected decimal MaxDepositAmount { get; set; }

protected decimal InteresetRate { get; set; }

// this variable will hold the summary of all the transaction that took place
protected string TransactionSummary { get; set; }

protected BankAccount(string accountOwnerName, string accountNumber)


{
AccountOwnerName = accountOwnerName;
AccountNumber = accountNumber;
TransactionSummary = string.Empty;
}

// Deposit is an abstract method so that Saving/Current Account must override


// it to give their specific implementation.
public abstract void Deposit(decimal amount);

// Withdraw is an abstract method so that Saving/Current Account must override


// it to give their specific implementation.
public abstract void Withdraw(decimal amount);

public decimal CalculateInterest()


{
return (this.AccountBalance * this.InteresetRate) / 100;
}

// This method adds a Reporting functionality


public virtual void GenerateAccountReport()
{
Console.WriteLine("Account Owner:{0}, Account Number:{1}, AccountBalance:{2}",
this.AccountOwnerName, this.AccountNumber, this.AccountBalance);

Console.WriteLine("Interest Amount:{0}", CalculateInterest());


Console.WriteLine("{0}", this.TransactionSummary);
}
}

Constructor: Though the BankAccount class is an abstract class, it still has a constructor. What is
the use of a constructor if an instance of the abstract class cannot be created? The constructor is
used when we create an instance of SavingAccount or CurrentAccount, so variables defined in
the abstract class could be initialized using the abstract class constructor. Remember that whenever a
child class is instantiated, the constructor of its base class is called first and then the derived class
constructor is called.

Some of the fields are protected and some are public, I have kept it like that for no serious
reason.TransactionSummary is kept protected so that only a child class should be able to see
and change it.

The GenerateAccountReport() method will show the details of the account including the
transaction summary. It is a virtual method. By setting it as virtual, we are declaring that any subclass
can override it to give its own implementation; however, the default implementation is provided by
the base class.

Let's now move to our child classes, i.e., SavingAccount and CurrentAccount:

Hide Shrink Copy Code

public class SavingBankAccount : BankAccount


{
protected int withdrawCount = 0;

public SavingBankAccount(string accountOwnerName, string accountNumber)


:base(accountOwnerName,accountNumber)
{
this.MinAccountBalance = 20000m;
this.MaxDepositAmount = 50000m;
InteresetRate = 3.5m;
}

public override void Deposit(decimal amount)


{
if (amount >= MaxDepositAmount)
{
throw new Exception(string.Format("You can not deposit amount
greater than {0}", MaxDepositAmount.ToString()));
}

AccountBalance = AccountBalance + amount;

TransactionSummary = string.Format("{0}\n Deposit:{1}",


TransactionSummary, amount);
}

public override void Withdraw(decimal amount)


{
// some hard coded logic that withdraw count should not be greater than 3
if (withdrawCount > 3)
{
throw new Exception("You can not withdraw amount more than thrice");
}

if (AccountBalance - amount <= MinAccountBalance)


{
throw new Exception("You can not withdraw amount from your
Savings Account as Minimum Balance limit is reached");
}

AccountBalance = AccountBalance - amount;


withdrawCount++;

TransactionSummary = string.Format("{0}\n Withdraw:{1}",


TransactionSummary, amount);
}
// This method adds details to the base class Reporting functionality
public override void GenerateAccountReport()
{
Console.WriteLine("Saving Account Report");
base.GenerateAccountReport();

// Send an email to user if Savings account balance is less


// than user specified balance this is different than MinAccountBalance
if(AccountBalance > 15000)
{
Console.WriteLine("Sending Email for Account {0}", AccountNumber);
}
}
}

Let's see our CurrentAccount class which also derives from the abstract base class.

Hide Shrink Copy Code

public class CurrentBankAccount : BankAccount


{
public CurrentBankAccount(string accountOwnerName, string accountNumber)
:base(accountOwnerName,accountNumber)
{
this.MinAccountBalance = 0m;
this.MaxDepositAmount = 100000000m;
InteresetRate = .25m;
}

public override void Deposit(decimal amount)


{
AccountBalance = AccountBalance + amount;
TransactionSummary = string.Format("{0}\n Deposit:{1}",
TransactionSummary, amount);
}

public override void Withdraw(decimal amount)


{
if (AccountBalance - amount <= MinAccountBalance)
{
throw new Exception("You can not withdraw amount from
your Current Account as Minimum Balance limit is reached");
}

AccountBalance = AccountBalance - amount;


TransactionSummary = string.Format("{0}\n Withdraw:{1}",
TransactionSummary, amount);
}
// This method adds details to the base class Reporting functionality
public override void GenerateAccountReport()
{
Console.WriteLine("Current Account Report");
base.GenerateAccountReport();
}
}

Let's dig inside our child classes. The constructors of the SavingAccount as well

as CurrentAccount are initializing some variable as per their requirements, however certain
common variables are set by the abstract class, which explains the rationale behind the need of a
constructor in the abstract class.

The Withdraw and Deposit methods are pretty simple and need no detailed explanation. Both
classes have overridden them to provide their own implementation.

The Deposit method of SavingAccount throws an exception if the amount deposited is greater
than a specified limit.

The Withdraw method of SavingAccount checks the number of withdrawals before throwing an
exception.

The GenerateAccountReport method of SavingAccount adds a report header, calls the base
class method for the generic implementation, and then sends the account report email.
To use the above code, here is a our Main method which creates an instance each of a Saving and
Current account. The variable taken to store these instance is of type BankAccount, thus allowing us
to have polymorphic behavior.

Hide Copy Code

public static void Main(string[] args)


{
BankAccount savingAccount = new SavingBankAccount("Sarvesh", "S12345");
BankAccount currentAccount = new CurrentBankAccount("Mark", "C12345");

savingAccount.Deposit(40000);
savingAccount.Withdraw(1000);
savingAccount.Withdraw(1000);
savingAccount.Withdraw(1000);

// Generate Report
savingAccount.GenerateAccountReport();

Console.WriteLine();
currentAccount.Deposit(190000);
currentAccount.Withdraw(1000);
currentAccount.GenerateAccountReport();

Console.ReadLine();
}

Here is the output


Hide Copy Code

Saving Account Report


Account Owner:Sarvesh, Account Number:S12345, AccountBalance:37000
Interest Amount:1295.0

Deposit:40000
Withdraw:1000
Withdraw:1000
Withdraw:1000
Sending Email for Account S12345

Current Account Report


Account Owner:Mark, Account Number:C12345, AccountBalance:189000
Interest Amount:472.50

Deposit:190000
Withdraw:1000

When to Use Abstract Class


Let's go back to the example of our banking application.
Though we cannot open a generic account, all accounts will have a certain member and behavior as
discussed above. Also, we want that all types of accounts should conform to these attributes and
behaviors.

To summarize, create an abstract class if:

1. Class expresses an idea which is too generic and whose independent (alone) existence is not
required in your application, e.g., BankAccount.
2. There is a family of types forming a hierarchy. An “IS-A” relation exists between a base class and
other derived classes. E.g.:
o Saving Account IS-A Bank Account
o Current Account IS-A Bank Account
3. If there are certain members/ behaviors which are common to all classes, these should be placed
inside the abstract class, e.g., AccountNumber, Deposit(), etc.
4. If there are behaviors/attributes which should be implemented or must be present in all classes,
declare them as abstract methods in the abstract class, e.g., CalculateInterest().

Why Not an Interface in Place of the


BankAccount Class?
In our example, you can argue that we can use a Interface instead of the BankAccount abstract
class, something like shown below:

Hide Copy Code

public class SavingBankAccount : IBankAccount


{
void Deposit(decimal amount);
void Withdraw(decimal amount);
decimal CalculateInterest();
}

First of all, there is a hierarchy between BankAccount and SavingAccount and a close relation
exists. Also, we are able to figure out certain common features present in all the child classes, thus an
abstract class will help in code reuse. An interface is more of a contract between classes. There are a
lot of syntactical differences between an abstract class and an interface, a little Googling may be of
great help so I haven't touched it in this article.
Inheritance
Inheritance means getting some thing (properties) as heredity. To get that, we need a hierarchical
structure. And that is provided by OOP using Inheritance. Here in inheritance, we have a concept of
base class and sub class. The base class is also known as parent class, super class, etc. and the sub
class is also known as child class. The properties (variables) and methods are accessible to the sub
class, but keep in mind that only the public ones. The private methods or variables are not accessible
from the child class. And the methods are accessible can be called without creating the object of that
super class.

To inherit a class from another class, you have to extend the sub class to super class. Follow the
example given below:

Hide Copy Code

class ClassSuper
{
public void MethdoTestPublic()
{
Console.WriteLine("ClassTest.MethdoTestPublic");
}

private void MethdoTestPrivate()


{
Console.WriteLine("ClassTest.MethdoTestPublic");
}
}

class ClassSub : ClassSuper // Inheriting from ClassSuper


{
public void MethodTest()
{
MethdoTestPublic(); // calling the super class method
MethdoTestPrivate(); // calling the super class private method [Error]
Console.WriteLine("ClassTest2.MethodTest");
}
}

Here, ClassSub is extending the ClassSuper to get access to the methods and properties of the
super class.

Type of Inheritance:

1. Single Inheritance
2. Multiple Inheritance
3. Multi Level Inheritance
4. Hierarchical Inheritance
Single Inheritance

The above example is one of the examples of Single Inheritance.

Hide Copy Code

class ClassSuper
{
// Do your code
}

class ClassSub : ClassSuper // Inheriting from ClassSuper


{
// Do your code
}

Multi Level Inheritance

Multi level inheritance is the joining of two or more single inheritance. Like Sub Class 2 is inheriting
Sub Class 1 and Sub Class 1 is inheriting Super Class. If you watch closely, there are two single
inheritances present. One is Sub Class 1 -> Sub Class 2 and second one is Sub Class 1 -> Super Class.
Hide Copy Code

class ClassSuper
{
// Do your code
}

class ClassSub1 : ClassSuper // Inheriting from ClassSuper


{
// Do your code
}
class ClassSub2 : ClassSub1 // Inheriting from ClassSub2
{
// Do your code
}

Hierarchical Inheritance

In case of Hierarchical interface, we have multiple sub classes which are inheriting one super class.
Like here Sub Class 1 and Sub Class 2, both are inheriting Super Class. This is Hierarchical Inheritance.
Hide Copy Code

class ClassSuper
{
// Do your code
}

class ClassSub1 : ClassSuper // Inheriting from ClassSuper


{
// Do your code
}
class ClassSub2 : ClassSuper // Inheriting from ClassSuper
{
// Do your code
}

Multiple Inheritance

Multiple Inheritance is just the opposite of Hierarchical Inheritance. Here one sub class is inheriting
multiple Super Classes. Like any other Object Oriented Programming languages, C# also doesn't
support Multiple Inheritance. To achieve that, we have to go for Interface, which we will discuss later.

Like here, the only Sub Class is inheriting the two Super Classes (Super Class 1 and Super Class 2).
This architecture is not possible with C# classes. So we are taking help of Interface to do so.

Hide Copy Code

interface ISuper1
{
// Do your code
}

interface ISuper2
{
// Do your code
}
class ClassSub : ISuper1, ISuper2 // Inheriting from ISuper1 and ISuper2
{
// Do your code
}
Advantages of Inheritance
1. Reusability: Use the base class public methods and properties from the base class, without defining
or creating any instance.
2. Extensibility: Extend the base class methods logic in the sub class without rewriting the same.
3. Data hiding: Base class can keep some data private so that it cannot be altered by the derived
class.
4. Override: Base class methods can be overridden by sub class methods to reuse in a meaningful way.

Disadvantages of Inheritance
1. Tightly Coupled: In inheritance, both the classes (sub and super class) are tightly coupled. So if any
change occurs in super class, it will affect in the base class.
2. Sometimes, a lot of data remains unused in the hierarchy. So memory wastage can happen in case of
inheritance.

What is Garbage Collection and Why We Need


It?
When you create any object in C#, CLR (common language runtime) allocates memory for the object
from heap. This process is repeated for each newly created object, but there is a limitation to
everything, Memory is not un-limited and we need to clean some used space in order to make room
for new objects, Here, the concept of garbage collection is introduced, Garbage collector manages
allocation and reclaiming of memory. GC (Garbage collector) makes a trip to the heap and collects all
objects that are no longer used by the application and then makes them free from memory.

Memory Facts

When any process gets triggered, separate virtual space is assigned to that process, from a physical
memory which is the same and used by every process of a system, any program deals with virtual
space not with physical memory, GC also deals with the same virtual memory to allocate and de-
allocate memory. Basically, there are free-blocks that exist in virtual memory (also known as holes),
when any object request for memory allocation manager searches for free-block and assigns
memory to the said object.

Virtual memory has three blocks:

 Free (empty space)


 Reserved (already allocated)
 Committed (This block is give-out to physical memory and not available for space allocation)

**You may face out of memory error due to virtual memory full.

How GC Works?

GC works on managed heap, which is nothing but a block of memory to store objects, when garbage
collection process is put in motion, it checks for dead objects and the objects which are no longer
used, then it compacts the space of live object and tries to free more memory.

Basically, heap is managed by different 'Generations', it stores and handles long-lived and short-lived
objects, see the below generations of Heap:

 0 Generation (Zero): This generation holds short-lived objects, e.g., Temporary objects.
GC initiates garbage collection process frequently in this generation.
 1 Generation (One): This generation is the buffer between short-lived and long-lived objects.
 2 Generation (Two): This generation holds long-lived objects like a static and global variable, that
needs to be persisted for a certain amount of time. Objects which are not collected in generation
Zero, are then moved to generation 1, such objects are known as survivors, similarly objects which
are not collected in generation One, are then moved to generation 2 and from there onwards objects
remain in the same generation.

How GC Decides If Objects Are Live?


GC checks the below information to check if the object is live:

 It collects all handles of an object that are allocated by user code or by CLR
 Keeps track of static objects, as they are referenced to some other objects
 Use stack provided by stack walker and JIT

When GC Gets Triggered?


There are no specific timings for GC to get triggered, GC automatically starts operation on the
following conditions:

1. When virtual memory is running out of space.


2. When allocated memory is suppressed acceptable threshold (when GC found if the survival rate
(living objects) is high, then it increases the threshold allocation).
3. When we call GC.Collect() method explicitly, as GC runs continuously, we actually do not need to
call this method.

What is Managed and Unmanaged


Objects/Resources?

VS

In simple terms:

Managed objects are created, managed and under scope of CLR, pure .NET code managed by
runtime, Anything that lies within .NET scope and under .NET framework classes such
as string, int, bool variables are referred to as managed code.

UnManaged objects are created outside the control of .NET libraries and are not managed by CLR,
example of such unmanaged code is COM objects, file streams, connection objects, Interop objects.
(Basically, third party libraries that are referred in .NET code.)
Clean Up Unmanaged Resources

When we create unmanaged objects, GC is unable to clear them and we need to release such objects
explicitly when we finished using them. Mostly unmanaged objects are wrapped/hide around
operating system resources like file streams, database connections, network related instances, handles
to different classes, registries, pointers etc. GC is responsible to track the life time of all managed and
unmanaged objects but still GC is not aware of releasing unmanaged resources

There are different ways to cleanup unmanaged resources:

 Implement IDisposable interface and Dispose method


 'using' block is also used to clean unmanaged resources

There are couple of ways to implement Dispose method:

 Implement Dispose using 'SafeHandle' Class (It is inbuilt abstract class which has
'CriticalFinalizerObject' and 'IDisposable' interface has been implemented)
 Object.Finalize method to be override (This method is clean unmanaged resources used by
particular object before it is destroyed)

Let's see below code to Dispose unmanaged resources:

 Implement Dispose using 'SafeHandle' Class:


Hide Shrink Copy Code
class clsDispose_safe
{
// Take a flag to check if object is already disposed
bool bDisposed = false;

// Create a object of SafeHandle class


SafeHandle objSafeHandle = new SafeFileHandle(IntPtr.Zero, true);

// Dispose method (public)


public void Dispose1()
{
Dispose(true);
GC.SuppressFinalize(this);
}

// Dispose method (protected)


protected virtual void Dispose(bool bDispose)
{
if (bDisposed)
return;

if (bDispose)
{
objSafeHandle.Dispose();
// Free any other managed objects here.
}

// Free any unmanaged objects here.


//
bDisposed = true;
}
}

 Implement Dispose using overriding the 'Object.Finalize' method:


Hide Shrink Copy Code
class clsDispose_Fin
{
// Flag: Has Dispose already been called?
bool disposed = false;

// Public implementation of Dispose pattern callable by consumers.


public void Dispose()
{
Dispose1(true);
GC.SuppressFinalize(this);
}

// Protected implementation of Dispose pattern.


protected virtual void Dispose1(bool disposing)
{
if (disposed)
return;

if (disposing)
{
// Free any other managed objects here.
//
}

// Free any unmanaged objects here.


//
disposed = true;
}

~clsDispose_Fin()
{
Dispose1(false);
}
}

'using' Statement
using statement ensures object dispose, in short, it gives a comfort way of use
of IDisposable objects. When an Object goes out of scope, Dispose method will get called
automatically, basically using block does the same thing as 'TRY...FINALLY' block. To demonstrate it,
create a class with IDisposable implementation (it should have Dispose() method), 'using'
statement calls 'dispose' method even if exception occurs.

See the below snippet:

Hide Shrink Copy Code


class testClass : IDisposable
{
public void Dispose()
{
// Dispose objects here
// clean resources
Console.WriteLine(0);
}
}

//call class
class Program
{
static void Main()
{
// Use using statement with class that implements Dispose.
using (testClass objClass = new testClass())
{
Console.WriteLine(1);
}
Console.WriteLine(2);
}
}

//output
1
0
2

//it is same as below TRY...Finally code


{
clsDispose_Fin objClass = new clsDispose_Fin();
try
{
//code goes here
}
finally
{
if (objClass != null)
((IDisposable)objClass).Dispose();
}
}

In the above sample after printing 1, using block gets end and calls Dispose method and then call
statement after using.

Re-view

 Garbage collector manages allocation and reclaim of memory.


 GC works on managed heap, which is nothing but a block of memory to store objects.
 There is no specific timings for GC to get triggered, GC automatically start operation.
 Managed objects are created, managed and under scope of CLR.
 Unmanaged objects are wrapped around operating system resources like file streams, database
connections, network related instances, handles to different classes, registries, pointers, etc.
 Unmanaged resources can be cleaned-up using 'Dispose' method and 'using' statement.

Introduction
In this post, you will learn the following topics:

1. Polymorphism
2. Static or compile time polymorphism
o Method overloading
3. Dynamic or runtime polymorphism
o Method overriding
4. Virtual keyword and virtual method
5. Difference between method overriding and method hiding
6. Sealed method

What is Polymorphism?
Polymorphism means one name many forms. Polymorphism means one object behaving as multiple
forms. One function behaves in different forms. In other words, "Many forms of a single object is
called Polymorphism."

Real World Example of Polymorphism


Example 1
 A Teacher behaves with student.
 A Teacher behaves with his/her seniors.

Here teacher is an object but the attitude is different in different situations.

Example 2
 Person behaves as a SON in house, at the same time that person behaves like an EMPLOYEE in the
office.

Example 3

Your mobile phone, one name but many forms:

 As phone
 As camera
 As mp3 player
 As radio

With polymorphism, the same method or property can perform different actions depending on the
run-time type of the instance that invokes it.

There are two types of polymorphism:

1. Static or compile time polymorphism


2. Dynamic or runtime polymorphism
Static or Compile Time Polymorphism

In static polymorphism, the decision is made at compile time.

 Which method is to be called is decided at compile-time only.


 Method overloading is an example of this.
 Compile time polymorphism is method overloading, where the compiler knows which overloaded
method it is going to call.

Method overloading is a concept where a class can have more than one method with the same name
and different parameters.

Compiler checks the type and number of parameters passed on to the method and decides which
method to call at compile time and it will give an error if there are no methods that match the
method signature of the method that is called at compile time.

Example
Hide Shrink Copy Code

namespace MethodOverloadingByManishAgrahari
{
class Program
{
public class TestOverloading
{

public void Add(string a1, string a2)


{
Console.WriteLine("Adding Two String :" + a1 + a2);
}

public void Add(int a1, int a2)


{
Console.WriteLine("Adding Two Integer :" + a1 + a2);
}

}
static void Main(string[] args)
{
TestOverloading obj = new TestOverloading();

obj.Add("Manish " , "Agrahari");

obj.Add(5, 10);

Console.ReadLine();
}
}
}

Dynamic or Runtime Polymorphism

Run-time polymorphism is achieved by method overriding.

Method overriding allows us to have methods in the base and derived classes with the same name
and the same parameters.

By runtime polymorphism, we can point to any derived class from the object of the base class at
runtime that shows the ability of runtime binding.

Through the reference variable of a base class, the determination of the method to be called is based
on the object being referred to by reference variable.

Compiler would not be aware whether the method is available for overriding the functionality or not.
So compiler would not give any error at compile time. At runtime, it will be decided which method to
call and if there is no method at runtime, it will give an error.

See the following example:

Hide Shrink Copy Code

namespace PolymorphismByManishAgrahari
{
class Program
{
public class Base
{
public virtual void Show()
{
Console.WriteLine("Show From Base Class.");
}
}

public class Derived : Base


{
public override void Show()
{
Console.WriteLine("Show From Derived Class.");
}
}
static void Main(string[] args)
{
Base objBase;
objBase = new Base();
objBase.Show();// Output ----> Show From Base Class.

objBase = new Derived();


objBase.Show();//Output--> Show From Derived Class.

Console.ReadLine();
}
}
}

Compiler demands virtual Show() method and it compiles successfully. The right version
of Show() method cannot be determined until run-time since only at that time Base objBase is
initialized as Derived.

Virtual Keyword

According to MSDN, “The virtual keyword is used to modify a method, property, indexer or event
declaration, and allow it to be overridden in a derived class.”

Virtual Method

Virtual method is a method whose behavior can be overridden in derived class. Virtual method
allows declare a method in base class that can be redefined in each derived class.

When a virtual method is invoked, the run-time type of the object is checked for an overriding
member. The overriding member in the most derived class is called, which might be the original
member, if no derived class has overridden the member.

 By default, methods are non-virtual. You cannot override a non-virtual method.


 You cannot use the virtual modifier with the static, abstract, private or override modifiers.
 Virtual properties behave like abstract methods, except for the differences in declaration and
invocation syntax.
 It is an error to use the virtual modifier on a static property.
 A virtual inherited property can be overridden in a derived class by including a property
declaration that uses the override modifier.

Virtual method solves the following problem:

In OOP, when a derived class inherits from a base class, an object of the derived class may be
referred to (or cast) as either being the base class type or the derived class type. If there are base
class methods overridden by the derived class, the method call behavior is ambiguous.

In C#, polymorphism is explicit - you must have a virtual (or abstract) modifier on the base
class method (member) and an override on the derived class method, which you probably already
know.

If you don't put a modifier on a base class method, polymorphism can't ever happen. If you then add
a non-modified method to the derived class with the same signature as the non-modified base class
method, the compiler will generate a Warning message.

See the following example:

Hide Shrink Copy Code

namespace PolymorphismByManishAgrahari
{
class Program
{
public class Base
{

public void Show()


{
Console.WriteLine("Show From Base Class.");
}
}

public class Derived : Base


{
//Following line will Give an Warning
/*
'PolymorphismByManishAgrahari.Program.Derived.Show()'
hides inherited member
'PolymorphismByManishAgrahari.Program.Base.Show()'.
Use the new keyword if hiding was intended.
*/
public void Show()
{
Console.WriteLine("Show From Derived Class.");
}
}
static void Main(string[] args)
{
Base objBase = new Base();
objBase.Show();// Output ----> Show From Base Class.

Derived objDerived = new Derived();


objDerived.Show();//Output--> Show From Derived Class.

Base objBaseRefToDerived = new Derived();


objBaseRefToDerived.Show();//Output--> Show From Base Class.

Console.ReadLine();
}
}
}

It means that you are hiding (re-defining) the base class method.

In other languages, take Java for instance, you have what is called "implicit" polymorphism where just
putting the method in the derived class with the same signature as a base class method will enable
polymorphism.

In Java, all methods of a class are virtual by default unless the developer decides to use
the final keyword thus preventing subclasses from overriding that method. In contrast, C# adopts
the strategy used by C++ where the developer has to use the virtual keyword for subclasses to
override the method. Thus all methods in C# are non virtual by default.

The C# approach is more explicit for the purpose of making the code safer in versioning scenarios,
i.e., you build your code based on a 3rd party library and use meaningful, but common, method
names. The 3rd party library upgrades, using the same common method name. With implicit
polymorphism the code would break, but with C#, you would receive a compiler warning so you can
double check to see if polymorphism was something you wanted to do.

Difference between Method Overriding and Method Hiding

Method overriding allows a subclass to provide a specific implementation of a method that is already
provided by base class. The implementation in the subclass overrides (replaces) the implementation
in the base class.

The important thing to remember about overriding is that the method that is doing the overriding is
related to the method in the base class.

When a virtual method is called on a reference, the actual type of the object to which the reference
refers is used to determine which method implementation should be used. When a method of a base
class is overridden in a derived class (subclass), the version defined in the derived class is used. This is
so even should the calling application be unaware that the object is an instance of the derived class.

Hide Shrink Copy Code

namespace PolymorphismByManishAgrahari
{
class Program
{
public class Base
{

public virtual void Show()


{
Console.WriteLine("Show From Base Class.");
}
}

public class Derived : Base


{
//the keyword "override" change the base class method.
public override void Show()
{
Console.WriteLine("Show From Derived Class.");
}
}
static void Main(string[] args)
{
Base objBaseRefToDerived = new Derived();
objBaseRefToDerived .Show();//Output--> Show From Derived Class.

Console.ReadLine();
}
}
}

Output--> Show From Derived Class

Method hiding does not have a relationship between the methods in the base class and derived
class. The method in the derived class hides the method in the base class.

Hide Shrink Copy Code

namespace PolymorphismByManishAgrahari
{
class Program
{
public class Base
{

public virtual void Show()


{
Console.WriteLine("Show From Base Class.");
}
}

public class Derived : Base


{

public new void Show()


{
Console.WriteLine("Show From Derived Class.");
}
}
static void Main(string[] args)
{
Base objBaseRefToDerived = new Derived();
objBaseRefToDerived .Show();//Output--> Show From Base Class.

Console.ReadLine();
}
}
}

Output is:? Show From Base Class.

In the preceding example, Derived.Show will be called; because, it overrides Base.Show.

The C# language specification states that "You cannot override a non-virtual method." See the
following example:

Hide Shrink Copy Code

namespace PolymorphismByManishAgrahari
{
class Program
{
public class Base
{

public void Show()


{
Console.WriteLine("This is Base Class.");
}
}

public class Derived : Base


{
//Following Line will give error.
/*
Error:- 'PolymorphismByManishAgrahari.Program.Derived.Show()'
cannot override inherited member 'PolymorphismByManishAgrahari.Program.Base.Show()'
* because it is not marked virtual, abstract, or override
*/
public override void Show()
{

Console.WriteLine("This is Derived Class.");


}
}
static void Main(string[] args)
{
Base objBase = new Base();
objBase.Show();// Output ----> This is Base Class.

Derived objDerived = new Derived();


objDerived.Show();//Output--> This is Derived Class.

Base objBaseRefToDerived = new Derived();


objBaseRefToDerived.Show();//Output--> This is Base Class.

Console.ReadLine();
}
}
}

Error: 'PolymorphismByManishAgrahari.Program.Derived.Show() ' cannot override inherited


member 'PolymorphismByManishAgrahari.Program.Base.Show() ' because it is not
marked virtual, abstract, or override.

Sealed Keyword

Sealed keyword can be used to stop method overriding in a derived classes.

By default, all methods are sealed, which means you can't override them, so that "sealed" keyword
is redundant in this case and compiler will show you an error when you'll try to
make sealed already sealedmethod. But if your method was marked as virtual in a base class,
by overriding and marking this method with "sealed" will prevent method overriding in derived
classes.

See the following example:

Hide Shrink Copy Code

namespace PolymorphismByManishAgrahari
{
class Program
{
public class Base
{

public sealed void Show()//This Line will give an error - "cannot


{ //be sealed because it is not an override"

Console.WriteLine("This is Base Class.");


}
}

public class Derived : Base


{
public void Show()
{

Console.WriteLine("This is Derived Class.");


}
}
static void Main(string[] args)
{
Base objBaseReference = new Derived();
objBaseReference.Show();// Output ---------> This is Base Class.

Console.ReadLine();
}
}
}

Error: 'PolymorphismByManishAgrahari.Program.Base.Show() ' cannot be sealed because it


is not an override.

To remove error from the above program, use the following:

Hide Shrink Copy Code

namespace PolymorphismByManishAgrahari
{
class Program
{
public class Base
{

public virtual void Show()


{
Console.WriteLine("This is Base Class.");
}
}

public class Derived : Base


{
public override sealed void Show()
{

Console.WriteLine("This is Derived Class.");


}
}

static void Main(string[] args)


{
Base objBaseReference = new Derived();
objBaseReference.Show();// Output ---> This is Derived Class.

Console.ReadLine();
}
}
}

Output ---> This is Derived Class.

Summary
1. It is not compulsory to mark the derived/child class function with override keyword while
base/parent class contains a virtual method.
2. Virtual methods allow subclasses to provide their own implementation of that method using
the override keyword.
3. Virtual methods can't be declared as private.
4. You are not required to declare a method as virtual. But, if you don't, and you derive from the
class, and your derived class has a method by the same name and signature, you'll get a warning that
you are hiding a parent's method.
5. A virtual property or method has an implementation in the base class, and can be overridden in
the derived classes.
6. We will get a warning if we won't use Virtual/New keyword.
7. Instead of Virtual, we can use New keyword.

What is a Delegate?
Delegate is a type which holds the method(s) reference in an object. It is also referred to as a type
safe function pointer.

Advantages
 Encapsulating the method's call from caller
 Effective use of delegate improves the performance of application
 Used to call a method asynchronously

Declaration
Hide Copy Code

public delegate type_of_delegate delegate_name()

Example:

Hide Copy Code

public delegate int mydelegate(int delvar1,int delvar2)

Note
 You can use delegates without parameters or with parameter list
 You should follow the same syntax as in the method
(If you are referring to the method with two int parameters and int return type, the delegate
which you are declaring should be in the same format. This is why it is referred to as type safe
function pointer.)

Sample Program using Delegate


Hide Copy Code
public delegate double Delegate_Prod(int a,int b);
class Class1
{
static double fn_Prodvalues(int val1,int val2)
{
return val1*val2;
}
static void Main(string[] args)
{
//Creating the Delegate Instance
Delegate_Prod delObj = new Delegate_Prod(fn_Prodvalues);
Console.Write("Please Enter Values");
int v1 = Int32.Parse(Console.ReadLine());
int v2 = Int32.Parse(Console.ReadLine());
//use a delegate for processing
double res = delObj(v1,v2);
Console.WriteLine ("Result :"+res);
Console.ReadLine();
}
}

Explanation

Here I have used a small program which demonstrates the use of delegate.

The delegate "Delegate_Prod" is declared with double return type and accepts only two integer
parameters.

Inside the class, the method named fn_Prodvalues is defined with double return type and two
integer parameters. (The delegate and method have the same signature and parameter type.)

Inside the Main method, the delegate instance is created and the function name is passed to the
delegate instance as follows:

Hide Copy Code

Delegate_Prod delObj = new Delegate_Prod(fn_Prodvalues);

After this, we are accepting the two values from the user and passing those values to the delegate as
we do using method:

Hide Copy Code

delObj(v1,v2);

Here delegate object encapsulates the method functionalities and returns the result as we specified
in the method.
Multicast Delegate
What is Multicast Delegate?

It is a delegate which holds the reference of more than one method.

Multicast delegates must contain only methods that return void, else there is a run-time exception.

Simple Program using Multicast Delegate


Hide Copy Code

delegate void Delegate_Multicast(int x, int y);


Class Class2
{
static void Method1(int x, int y)
{
Console.WriteLine("You r in Method 1");
}

static void Method2(int x, int y)


{
Console.WriteLine("You r in Method 2");
}

public static void <place w:st="on" />Main</place />

Explanation

In the above example, you can see that two methods are defined
named method1 and method2 which take two integer parameters and return type as void.

In the main method, the Delegate object is created using the following statement:

Hide Copy Code

Delegate_Multicast func = new Delegate_Multicast(Method1);

Then the Delegate is added using the += operator and removed using the -= operator.

Conclusion
This article would help to understand delegates in C# using simple examples. If you have any query
regarding this article, you can reach me at [email protected].
Introduction
Method hiding in C# is similar to the function overriding feature in C++. Functions of the base class
are available to the derived class. If the derived class is not happy, one of the functions available to it
from the base class can define its own version of the same function with the same function signature,
just differing in implementation. This new definition hides the base class definition. Take the
following program for example.

P1.cs
Hide Copy Code

class BC
{
public void Display()
{
System.Console.WriteLine("BC::Display");
}
}

class DC : BC
{

class Demo
{
public static void Main()
{
DC obj = new DC();
obj.Display();
}
}

Output
Hide Copy Code

BC::Display

The above program compiles and runs successfully to give the desired output. The above program
consists of a base class BC which consists of a public function named Display(). Class DC is derived
from BC. So Display()of BC is Inherited by Class DC. It's as if DC has a function called Display().
Class Demo has the entry point function Main(). Inside Main we create an object obj of class DC and
invoke the function Display(). What is called is the Display of BC because its inherited by the
derived class DC.

For some unknown reason the derived class was not happy with the implementation of
the Display() function that it had inherited from its Base class BC. So the derived class made a
bold decision to define its own version of the function Display(). Thus, you could see code
for Display() function in class BC as well as in class DC.

P2.cs
Hide Copy Code

class BC
{
public void Display()
{
System.Console.WriteLine("BC::Display");
}
}

class DC : BC
{
public void Display()
{
System.Console.WriteLine("DC::Display");
}
}

class Demo
{
public static void Main()
{
DC obj = new DC();
obj.Display();
}
}

Output
Hide Copy Code

DC::Display

On compilation the above program threw a warning which said

Hide Copy Code

P2.cs(11,15): warning CS0108: 'DC.Display()' hides inherited member


'BC.Display()'. Use the new keyword if hiding was intended. P2.cs(3,15):
(Location of symbol related to previous warning)

The compiler warns us about Display() of DC forcibly hiding Display() of BC. The compiler
smells something dicy and requests us to use the new keyword if the hiding was intentional.

The above program compiles to produce an executable. We run the executable to get the desired
output as shown above. The Display() of derived class DC is invoked as it hides the Display() of
base class BC. But an executable with warnings is like a neatly dressed man with unpolished shoes.
We need to remove the warning. We need to tell the compiler that the implementation
of Display() in derived class was intentional. We do this by using the modifier new as shown in the
program below.

P3.cs
Hide Copy Code

class BC
{
public void Display()
{
System.Console.WriteLine("BC::Display");
}
}

class DC : BC
{
new public void Display()
{
System.Console.WriteLine("DC::Display");
}
}

class Demo
{
public static void Main()
{
DC obj = new DC();
obj.Display();
}
}

Output
Hide Copy Code

DC::Display

The addition of the modifier new to the function Display() in Derived class informs the compiler
that the implementation of Display() in Derived class was intentional, thus stopping the compiler
from throwing any warnings at us. Can you tell what the output of the above program will be?

P4.cs
Hide Shrink Copy Code

class BC
{
public void Display()
{
System.Console.WriteLine("BC::Display");
}
}

class DC : BC
{
new public void Display()
{
System.Console.WriteLine("DC::Display");
}
}

class TC : DC
{

class Demo
{
public static void Main()
{
TC obj = new TC();
obj.Display();
}
}

Output
Hide Copy Code

DC::Display

The above program compiles and runs successfully to give the desired output. Class TC is derived
from DC. So Display() of DC is Inherited by Class TC. It's as if TC has a function called Display().
Class Demo has the entry point function Main(). Inside Main we create an object obj of
class TC and invoke the function Display(). What gets called is the Display of DC because its
inheritted by the derived class TC. Now what if we were to define and invoke class TC's own version
of Display() ? Simple! We would have to define a function Displayinside class TC with a new
modifier as follows.

P5.cs
Hide Shrink Copy Code

class BC
{
public void Display()
{
System.Console.WriteLine("BC::Display");
}
}

class DC : BC
{
new public void Display()
{
System.Console.WriteLine("DC::Display");
}
}
class TC : DC
{
new public void Display()
{
System.Console.WriteLine("TC::Display");
}
}

class Demo
{
public static void Main()
{
TC obj = new TC();
obj.Display();
}
}

Output
Hide Copy Code

TC::Display

The above program comples and runs successfully to give the desired output.

Introduction

The keywords ref and out are used to pass arguments within a method or function. Both
indicate that an argument / parameter is passed by reference. By default parameters are
passed to a method by value. By using these keywords (ref and out) we can pass a
parameter by reference.

Ref Keyword

The ref keyword passes arguments by reference. It means any changes made to this
argument in the method will be reflected in that variable when control returns to the calling
method.

Example code

public static string GetNextName(ref int id)


{
string returnText = "Next-" + id.ToString();
id += 1;
return returnText;
}
static void Main(string[] args)
{
int i = 1;
Console.WriteLine("Previous value of integer i:" + i.ToString());
string test = GetNextName(ref i);
Console.WriteLine("Current value of integer i:" + i.ToString());
}

Output

Out Keyword

The out keyword passes arguments by reference. This is very similar to the ref keyword.

Example Code

public static string GetNextNameByOut(out int id)


{
id = 1;
string returnText = "Next-" + id.ToString();
return returnText;
}

static void Main(string[] args)


{
int i = 0;
Console.WriteLine("Previous value of integer i:" + i.ToString());
string test = GetNextNameByOut(out i);
Console.WriteLine("Current value of integer i:" + i.ToString());
}

Output

Ref Vs Out

Ref Out
The parameter or argument must be initialized It is not compulsory to initialize a parameter or
first before it is passed to ref. argument before it is passed to an out.
It is not required to assign or initialize the value of A called method is required to assign or initialize a
a parameter (which is passed by ref) before value of a parameter (which is passed to an out) before
returning to the calling method. returning to the calling method.
Passing a parameter value by Ref is useful when Declaring a parameter to an out method is useful when
the called method is also needed to modify the multiple values need to be returned from a function or
pass parameter. method.
It is not compulsory to initialize a parameter value A parameter value must be initialized within the calling
before using it in a calling method. method before its use.
When we use OUT data is passed only in a
When we use REF, data can be passed bi-
unidirectional way (from the called method to the
directionally.
caller method).
Both ref and out are treated differently at run time and they are treated the same at compile time.
Properties are not variables, therefore it cannot be passed as an out or ref parameter.

Ref / Out keyword and method Overloading

Both ref and out are treated differently at run time and they are treated the same at compile
time, so methods cannot be overloaded if one method takes an argument as ref and the
other takes an argument as an out.

Example code

public static string GetNextName(ref int id)


{
string returnText = "Next-" + id.ToString();
id += 1;
return returnText;
}

public static string GetNextName(out int id)


{
id = 1;
string returnText = "Next-" + id.ToString();
return returnText;
}

Output when the code is compiled:

However, method overloading can be possible when one method takes a ref or out
argument and the other takes the same argument without ref or out.

Example Code

public static string GetNextName(int id)


{
string returnText = "Next-" + id.ToString();
id += 1;
return returnText;
}
public static string GetNextName(ref int id)
{
string returnText = "Next-" + id.ToString();
id += 1;
return returnText;
}

Summary

The out and ref keywords are useful when we want to return a value in the same variables
as are passed as an argument.

What are collections and generics?

A collection can be defined as a group of related items that can be referred to as a single unit.
The System.Collections namespace provides you with many classes and interfaces. Some of
them are - ArrayList, List, Stack, ICollection, IEnumerable, andIDictionary. Generics
provide the type-safety to your class at the compile time. While creating a data structure, you never
need to specify the data type at the time of declaration.
The System.Collections.Generic namespace contains all the generic collections.

What is the difference between arrays and collection?

Array:

You need to specify the size of an array at the time of its declaration. It cannot be resized dynamically.

The members of an array should be of the same data type.

Collection:

The size of a collection can be adjusted dynamically, as per the user's requirement. It does not have
fixed size.
Collection can have elements of different types.

Named and optional parameters in C# 4.0

Introduction
In this article, I will explore named and optional parameters in C# 4.0. Named and optional
parameters are really two distinct features, and allow us to either omit parameters which have a
defined default value, and/or to pass parameters by name rather than position. Named parameters
are passed by name instead of relying on its position in the parameter list, whereas optional
parameters allow us to omit arguments to members without having to define a specific overload
matching.

Let’s have a look at Optional parameters:

Hide Copy Code

//In old way we will write the code as shown below.


public static double MyOldCurrencyExchange(double amount, double rate)
{
return (amount * rate);
}

We will call the above method as shown below:

Hide Copy Code

MyOldCurrencyExchange(500, 1.18);

Now, by using Optional parameters:

Hide Copy Code

//In new way we will write the code as shown below


public static double MyNewCurrencyExchange(double amount, double rate=1)
{
return (amount * rate);
}

We will call the above method as shown below:


Hide Copy Code

MyNewCurrencyExchange (500, 1.18); // ordinary call


MyNewCurrencyExchange (500); // omitting rate

Now, by using Named parameters:

Hide Copy Code

MyNewCurrencyExchange (rate:1.18, amount:500); // reversing the order of arguments.

Now, by using Named and Optional parameters:

Hide Copy Code

MyNewCurrencyExchange (amount:500);

All about abstract classes

Introduction
Abstract classes are one of the essential behaviors provided by .NET. Commonly, you would like to
make classes that only represent base classes, and don’t want anyone to create objects of these class
types. You can make use of abstract classes to implement such functionality in C# using the modifier
'abstract'.

An abstract class means that, no object of this class can be instantiated, but can make derivations of
this.

An example of an abstract class declaration is:

Hide Copy Code

abstract class absClass


{
}

An abstract class can contain either abstract methods or non abstract methods. Abstract members
do not have any implementation in the abstract class, but the same has to be provided in its derived
class.
An example of an abstract method:

Hide Copy Code

abstract class absClass


{
public abstract void abstractMethod();
}

Also, note that an abstract class does not mean that it should contain abstract members. Even we can
have an abstract class only with non abstract members. For example:

Hide Copy Code

abstract class absClass


{
public void NonAbstractMethod()
{
Console.WriteLine("NonAbstract Method");
}
}

A sample program that explains abstract classes:

Hide Shrink Copy Code

using System;

namespace abstractSample
{
//Creating an Abstract Class
abstract class absClass
{
//A Non abstract method
public int AddTwoNumbers(int Num1, int Num2)
{
return Num1 + Num2;
}

//An abstract method, to be


//overridden in derived class
public abstract int MultiplyTwoNumbers(int Num1, int Num2);
}

//A Child Class of absClass


class absDerived:absClass
{
[STAThread]
static void Main(string[] args)
{
//You can create an
//instance of the derived class

absDerived calculate = new absDerived();


int added = calculate.AddTwoNumbers(10,20);
int multiplied = calculate.MultiplyTwoNumbers(10,20);
Console.WriteLine("Added : {0},
Multiplied : {1}", added, multiplied);
}

//using override keyword,


//implementing the abstract method
//MultiplyTwoNumbers
public override int MultiplyTwoNumbers(int Num1, int Num2)
{
return Num1 * Num2;
}
}
}

In the above sample, you can see that the abstract class absClass contains two
methods AddTwoNumbers and MultiplyTwoNumbers. AddTwoNumbers is a non-abstract method
which contains implementation and MultiplyTwoNumbers is an abstract method that does not
contain implementation.

The class absDerived is derived from absClass and the MultiplyTwoNumbers is implemented
on absDerived. Within the Main, an instance (calculate) of the absDerived is created, and
calls AddTwoNumbers and MultiplyTwoNumbers. You can derive an abstract class from another
abstract class. In that case, in the child class it is optional to make the implementation of the abstract
methods of the parent class.

Example
Hide Copy Code

//Abstract Class1
abstract class absClass1
{
public abstract int AddTwoNumbers(int Num1, int Num2);
public abstract int MultiplyTwoNumbers(int Num1, int Num2);
}

//Abstract Class2
abstract class absClass2:absClass1
{
//Implementing AddTwoNumbers
public override int AddTwoNumbers(int Num1, int Num2)
{
return Num1+Num2;
}
}

//Derived class from absClass2


class absDerived:absClass2
{
//Implementing MultiplyTwoNumbers
public override int MultiplyTwoNumbers(int Num1, int Num2)
{
return Num1*Num2;
}
}

In the above example, absClass1 contains two abstract


methods AddTwoNumbers and MultiplyTwoNumbers. The AddTwoNumbers is implemented in the
derived class absClass2. The class absDerived is derived from absClass2 and
the MultiplyTwoNumbers is implemented there.

Abstract properties
Following is an example of implementing abstract properties in a class.

Hide Copy Code

//Abstract Class with abstract properties


abstract class absClass
{
protected int myNumber;
public abstract int numbers
{
get;
set;
}
}

class absDerived:absClass
{
//Implementing abstract properties
public override int numbers
{
get
{
return myNumber;
}
set
{
myNumber = value;
}
}
}

In the above example, there is a protected member declared in the abstract class.
The get/set properties for the member variable myNumber is defined in the derived
class absDerived.

Important rules applied to abstract classes


An abstract class cannot be a sealed class. I.e. the following declaration is incorrect.
Hide Copy Code

//Incorrect
abstract sealed class absClass
{
}

Declaration of abstract methods are only allowed in abstract classes.

An abstract method cannot be private.

Hide Copy Code

//Incorrect
private abstract int MultiplyTwoNumbers();

The access modifier of the abstract method should be same in both the abstract class and its derived
class. If you declare an abstract method as protected, it should be protected in its derived class.
Otherwise, the compiler will raise an error.

An abstract method cannot have the modifier virtual. Because an abstract method is implicitly
virtual.

Hide Copy Code

//Incorrect
public abstract virtual int MultiplyTwoNumbers();

An abstract member cannot be static.

Hide Copy Code

//Incorrect
publpublic abstract static int MultiplyTwoNumbers();

Abstract class vs. Interface


An abstract class can have abstract members as well non abstract members. But in an interface all the
members are implicitly abstract and all the members of the interface must override to its derived
class.

An example of interface:

Hide Copy Code


interface iSampleInterface
{
//All methods are automaticall abstract
int AddNumbers(int Num1, int Num2);
int MultiplyNumbers(int Num1, int Num2);
}

Defining an abstract class with abstract members has the same effect to defining an interface.

The members of the interface are public with no implementation. Abstract classes can have
protected parts, static methods, etc.

A class can inherit one or more interfaces, but only one abstract class.

Abstract classes can add more functionality without destroying the child classes that were using the
old version. In an interface, creation of additional functions will have an effect on its child classes,
due to the necessary implementation of interface methods to classes.

The selection of interface or abstract class depends on the need and design of your project. You can
make an abstract class, interface or combination of both depending on your needs.

Interfaces and Abstract Classes

Introduction
I often see people asking what's the difference between an interface and an abstract class and most
answers only focus on the different traits, not on how to use them.

That is, most answers will tell things like:

 An abstract class can have an implementation while an interface can't;


 In .NET we don't have multiple inheritance, so we can't use multiple abstract base classes, but we can
implement multiple interfaces;
 An interface is a contract, an abstract class is more than that (this one actually says nothing useful to
me, but it is a common answer).

Well, there are many other answers that go in the same direction. Independently how correct those
answers are, they don't answer the real question (even if sometimes it isn't asked explicitly):

When should we use an interface and when should we use an abstract class?
Short answer: If we want to create a method that receives an object to call one or more of its
methods, expecting those methods to have different implementations according to the received
object, we should ask for an interface. Now, if we need to provide an object for such method, we
should prefer implementing an abstract class instead of implementing the interface directly.

I know, that short answer is not very clear and doesn't explain why do that, so this article is all about
answering it.

Input arguments - Always use interfaces


Imagine that you are developing a system and, at certain moments, such system must generate logs.
I am not going to discuss if logging should be part of the main logic or not, what I am going to
discuss is the fact that you may write the log to a text file, to the database or to something else.

At this moment, you simply know that you want to be able to do things like these:

Hide Copy Code

logger.Log("An error happened in module X.");


logger.ConcatLog("An error happened in module ", moduleName, ".");
logger.FormatLog("An error happened in module {0}.", moduleName);

If it is not clear enough, the difference between the three methods is that the first receives only a
single string, the second receives a params array of objects that are concatenated together and the
third receives a string with placeholders (the {0}) and then an array of objects that will fill the
placeholders.

It is easy to write an interface for these methods:

Hide Copy Code

interface ILogger
{
void Log(string message);
void ConcatLog(params object[] messageParts);
void FormatLog(string format, params object[] parameters);
}

Note that at this moment you simply don't need to care at all how those will be implemented. You
only need an interface to be able to do the calls. If you think about other methods that you might
need, it is OK to add them to the interface right now. What you are saying is "I need to call these
methods and I don't care how they are implemented".
Abstract class - Provide a base implementation
for those who may want it
In my opinion, an abstract class is useful if you want to provide a basic implementation for an
interface when you believe some (or most) of its methods will be always implemented with the same
code or if you believe that new methods with default implementations may be added in the future.

For example, independently if we are going to log to a database, to a text file or even send messages
through TCP/IP, the methods ConcatLog() and FormatLog() may be implemented like this:

Hide Copy Code

public void ConcatLog(params object[] messageParts)


{
string message = string.Concat(messageParts);
Log(message);
}
public void FormatLog(string format, params object[] parameters)
{
string message = string.Format(format, parameters);
Log(message);
}

So, an abstract class can actually implement those two methods and keep the Log() method
abstract. Then, when developing the FileLogger, the DatabaseLogger and the TcpIpLogger any
developper may use the abstract class that implements two of the three methods to avoid repetitive
code.

Why not start with the abstract class?

Considering my example, a common question is: Why not start with the abstract class and avoid the
creation of an "useless" interface?

Well, who guarantees that the interface is useless?

For example, my actual implementation of those methods is not completely right. It doesn't validate
the input parameters, so if the ConcatLog() is called with null an ArgumentNullException will
be thrown saying that the args is null. But the ConcatLog() receives a messageParts, not
an args. A similar problem happens with the FormatLog(). Of course that we can solve that
problem by correcting the abstract class if we are its authors, but what happens if the abstract class is
comming in a compiled library and we are only the user of that library?

If the developers of the compiled library always receive things by an interface, independently on the
existence of the abstract class, we are free to completely reimplement the methods, giving the right
error messages if needed.
As another example, what about a NullLogger? That is, you give a logger as a parameter to a
method that expects a logger, yet your logger doesn't do anything.

You may implement a NullLogger with the abstract class, but two of the three methods will waste
time formatting/concatenating the message that will not be logged. A NullLogger that implements
all the interface methods to do nothing will be faster. This kind of "no action" object helps to avoid
checking for null and is so common that there's even a design pattern for it: Null Object Pattern.

Finally, we never know the kinds of statistics our users need. Imagine that someone wants to create a
logger that not only logs the message, it also logs how many times each one of the log methods was
called. If we start with the abstract class that always redirect to the Log() message, we will only be
able to count how many times the Log() method was called, independently if users were actually
calling the other methods. By fully implementing an interface, we will avoid this problem, as we can
generate the statistics for each method individually.

So, putting ourselves in the position of developers that give components to others, we must try to
give the components completely right and also allow users to reimplement anything they see fit, be
it because we made a mistake or simply because they have a special need.

An abstract class that comes with an implementation yet is fully virtual

A possible solution to the previous problem is to create an abstract class that implements
the ConcatLog() and the FormatLog() and still lets them be overriden (so, makes them virtual),
completely avoiding the existence of an interface.

This works pretty fine as users may reimplement any methods of the class. So, looking at this
problem in isolation, an abstract class that comes with an implementation but keeps all the methods
virtual is a better solution than an interface. But continue reading, as I will explore the differences
even further.

Future changes
Here is a big difference from an interface to an abstract class.

If a new method is added to an interface, all classes that implement it must change to include the
new method, even if all implementations are identical.

If a new method is added to an abstract class, as long as it comes with a default implementation,
nothing else needs to change. Users will simply see that there's a new method there that they can
invoke or override.

Of course, a new abstract method on an abstract class is as problematic as a new method in an


interface. But with default implementations, we can see that the abstract class has an advantage.
Yet, there's another question that we should ask: Why are we going to add another method to an
interface or abstract class?

It is guaranteed that already existing compiled code that's working with the old version of the
interface or abstract class is not going to call the new method, so why create such a breaking
change?

Well, I will try to list some reasons to do this:

1. The code is still under development and we simply saw that we need more methods (in this case, we
can say there's no "existing code" that will break);
2. The code is in a library given to many different users, and the users are asking for new
methods they consider to be missing (so, the users will use the new method as soon as it is
available);
3. We are changing the code that calls the actual interface or class and we want new variants of the
existing methods to make things faster;
4. Similar to the previous case, we are changing the code that calls the interfaces or abstract classes,
but now we see that we need new methods, which are simply impossible to be simulated with the
existing methods. It is not simply a question of performance;
5. We have many complaints that some methods have too many parameters and are hard to use, so
the users want easier to use overloads.

Well, I am pretty sure there are many other reasons, but I will stop here.

For the first situation, we can change things freely, as we didn't "close" the code yet. The only things
that will matter will be our purpose and our own rules regarding the possible evolution of the
application.

For the second situation I will use the .NET Stream class as example. In the first version it didn't
support timeouts, yet that was a very common need and it was added, having a default
implementation that says it doesn't support time-outs (CanTimeout returns false) and throws
an InvalidOperationException if we try to use the read or write timeout properties. It would be
wrong to change an already existing interface to add those properties, as this would break all the
existing implementations, yet it would be possible to create another interface with the extra
functionality. In any case, in .NET the Stream is an abstract class, not an interface, and the new
properties were added with a default implementation.

For the third situation, we can add those extra methods with a default implementation in an abstract
class. So, those who want to give the faster implementation can. Those who don't want will keep
their code working without changes. Unfortunately, changing an interface will cause breaking
changes. So we may ignore the change, keeping the slower speed, we may cause the breaking
change (and let some users furious) or we may add an extra interface, which our code will try to use
with a checked cast or else will use the "default" implementation. Unfortunately, again, adding an
extra interface and the interface lookup affects performance so, in some cases, we will lose the
performance boost that we were looking for.
For the fourth situation, we will have a breaking change using either an interface or an abstract class.
So there's no difference here.

For the fifth situation, we can solve the problem by adding extension methods that work as the
simpler to use overloads (this works for the interfaces and the classes, but users must add the
right using clause to see these extensions) and we can add them to the abstract class without
problems, even if they aren't virtual. Adding them to the interface will be a breaking change, but
compared to the extension methods has the advantage that if you see the interface, you can see all
the overloads.

Interface + Abstract class

Except for the fourth problem, which is always a breaking change, we can solve all the problems by
always having an interface + an abstract class, allowing us to add new methods that are virtual and
always visible (which is better than the extension methods).

It is not a problem to add a new method to an interface if all the implementations are based on an
abstract class that you are providing, as the abstract class can give the default implementation. This
can actually create a "design pattern" where for each interface there's an abstract class, even if it
doesn't give any default implementation in its first version.

So, those who prefer to revisit their code if the interface changes can implement it directly (and if
everything is well documented, they shouldn't blame you for breaking changes if/when the interface
changes). Users who prefer a "default behavior" instead of reviewing the interface changes simply
inherit from the abstract class. If this is done, we return to the short answer I gave in the beginning of
the article, in which method parameters should always use the interface, so they can support any
implementation (based on the abstract class or not), yet the implementations should try to use the
abstract class to avoid breaking changes.

Big or small interfaces? - Advanced


I finished with the direct differences between interfaces and abstract classes and I believe from this
point on the article becomes advanced. So, if you don't want to see the advanced text, you can jump
to the topic Summing it up.

Now I have a question, for which I know two opposite answers: Should we use big or small
interfaces?

I just talked about method overloads. Do you think interfaces should present all the possible
overloads or they should have only the method with most parameters and that the overloads should
be written in separate helper classes?

Many people will say that we should use the Interface Segregation Principle (also known as ISP) and
that we should only give the methods with most parameters, that any overload should be elsewhere.
Well, actually ISP doesn't talk about method overloads, it talks about interfaces that do more than
what they should do. For example, most of my IValueConverters used in WPF don't need
the ConvertBack() method because I use one-way bindings, yet the interface forces me to
implement such method throwing a NotSupportedException. It is not an overload of an existing
method, it is a method with a different purpose that's not used.

So, the overloads aren't necessarily an ISP violation, yet it became implicitly understood by those
who follow the principle that we should not put the overloads in the interface. This returns to the
problem already presented that we may not be able to monitor how many times each method was
called, as we will only be able to override the method with most parameters. Aside from that, how do
we make these extra methods accessible?

The normal solution now is to use extension methods. With extension methods we can "add"
methods with an implementation even to interfaces. Yet, they aren't real methods of the interface
and they will not appear to the user if the unit isn't using the right namespace. This may cause lots
of confusions to developers that know that an interface "has" a certain method but the calls are
simply not working.

Also, those methods are seen as "implementation" on top of the interface. That is, we are not
depending on interfaces, we are still depending on implementations (even if they are small) which
then depend on the interface.

So, we have two options:

 Small interfaces + extension methods: Any overload that simply fills some defaults is put as an
extension method and the interface stays intact. We will not break any code that depends on or
implements the interface, as the interface doesn't change. The new overloads will not be real
interface methods and users may not see them if they miss a using clause. Overriding those
overloads is not possible (but there's a work-around that I will present later);
 Big interfaces: Any overload is put as part of the interfaces. So, adding a new overload is a breaking
change for the interfaces, yet we can solve the trouble for those who want to implement them by
also giving abstract classes on top of the interfaces, which we will need to update when the
interfaces change. As the methods are part of the interfaces, they can always receive specific
implementation (useful to know exactly which methods are called and in remoting scenarios where it
is preferable to send less data instead of sending the defaults) and they are always visible when we
have access to the interface.

Contrary to what most developers say, I usually prefer the big interfaces, as long as I keep the
abstract classes to avoid the breaking changes. But I know, this is a personal preference.

Interface Segregation Principle (ISP) and


"overridable" extension methods
Extension methods are static methods written in static classes that can be invoked as if they were
member methods of their targeted types.

As they are static, they can't be overridden. Yet there's a work-around for this. The extension
method should first try to cast the received object to an interface that implements the same
functionality it does. If the cast is valid, it should use that version. If not, it continues with its own
implementation.

We can see this in some LINQ methods. For example, the ElementAt() method first tries to cast the
enumerable to an IList, which already has an indexer (very fast for lists and arrays) but when the
cast fails it enumerates the enumerable until it reaches the requested index.

To achieve this kind of functionality we usually keep a base interface with the minimum required
methods (in our example, an ILogger with only the Log() method) then we have sub-interfaces,
like IFormatLogger and IConcatLogger, each one with a single specialization (usually a single
method, but it is possible to have some related methods together).

With this approach we can extend base interfaces and still allow the "overridable" behavior at run-
time and, better yet, the extra methods could be added in different assemblies.

The bad parts of this approach are:

 When implementing the base interface, users may not be aware of all the extra methods that could
be overriden, which is even more problematic as users must know the extension method and the
interface used by such method;
 There's an extra interface lookup. Such lookup is usually pretty fast, but this means that creating
extra methods to add a little speed boost to the base interface may end-up not giving any benefit, as
we gain in the method itself but we lose with that extra lookup.

Interface Segregation Principle and Decoration


The Interface Segregation Principle splits large interfaces into many small interfaces. Independently
on the other discussions about abstract classes, interfaces, method overriding and performance this
technique has another problem: It interacts terribly with decoration.

Decoration is when we implement an interface (or even abstract class) to add some behavior and
then we redirect to another implementation. For example, we may use a decorator to count how
many times each method is invoked, used to generate statistics at the end of the application, yet we
keep calling the methods of another implementation to do the real job.

When we have a single class or interface with many methods we know how many methods we must
implement. But when we have many segregated interfaces, this is not so easy. We may need to have
decorators that implement exactly the same interfaces as the target objects, which is not viable in
many situations.
To let things clear, I will use the streams as example. In .NET it is a single Stream abstract class. In
Java we have many interfaces to represent the same thing. I will not focus on the Java version, but
the .NET Stream class could be divided into:

 Read part: As there are read-only streams;


 Write part: As there are write-only streams;
 Time out part: Both the read and the write parts may or may not support timing-out;
 Seeking: When dealing with files (and some other streams), we may "reposition" what we see on
that stream. In Video files, for example, we may go to the minute 45 without waiting for 45 minutes
and we may go back to the beginning at any moment. Yet, most of streams are forward only.

As everything is inside a single class in .NET, if we want to create a decorator we know that we must
simply inherit a single class and override all the methods that we can.

If we could have many different interface combinations, how would we create a decorator?

 If the decorator implements only the Read interface without implementing the Timeout one, it is not
important if the base object supports time-out, users of the decorator will not have access to the
timeout anymore;
 If the decorator implements the timeout interface, then users can simply assume that such instance
supports timeouts, but this will not be true if the decorated object doesn't have such a support.
Throwing exceptions when the timeout is configured seems wrong, as the decorator implements the
interface. Ignoring the timeout configuration when the inner stream doesn't support it is wrong too,
after all the code may be ignoring time-out alternatives because the decorator apparently supports
timeouts. Writing a default implementation for timeouts is too much and will possibly cause bugs if
there's no method to cancel a pending action (ow... I forgot to put an ICancellableStream in the list
of possibilities). Putting a CanTimeout inside a timeout interface is counter-intuitive, as users expect
to see that interface only when the object supports timing-out, after all many developers forget to
check if an object is not null, now imagine checking that an object is not null, that it implements an
interface and that it also has a CanTimeout of true.

So, should we create a decorator class per possible combination? That is, a decorator for the read
interface only, one for the read and timeout interface, one for write, one for read and write... and I
think you got the idea, this will require many, many implementations to give all the possible
combinations.

Should we only create decorators at run-time, analyzing the existing objects instead of hard-coding
them? This will make generating decorators pretty hard and it may not be possible in all situations,
as some constrained environments don't allow generating code at run-time.

Should all the interfaces have a CanSomething so decorators can implement all the interfaces and
still tell which actions they don't support? This is how the Stream class tells if it supports something
or not, but it is a single class with many possibilities. An interface with a single kind of action saying
that it doesn't support that action is awkward. And, if the decorators must have all the interfaces, why
not have a base class that lists all the possible actions with those CanSomething properties to start
with?
Well, that's what the .NET Stream class do. By not having independent interfaces, it is guaranteed
that all the Stream implementations will have all the same methods, even if some of them
throw NotSupportedExceptions.

So, for particular scenarios, abstract classes may still be a better option than segregated interfaces,
be it for the easiness to create adapters or by their performance.

Interface Segregation Principle + Easier


decoration
I already presented how it is possible to use "overridable" extension methods. So, why not extend the
concept even further to allow easier decoration?

Actually the biggest problem with decoration is the fact that the casts are done directly over the
received objects. So, either the object implements the interface or not. It doesn't have the chance to
say: "Hey, even if I implement the interface, in this particular situation ignore it".

That's what the CanSomething properties were trying to tell. But in a well done architecture the
interfaces will never need to have a property to tell if they work or not. Yet, the framework will not
simply cast the received instance to another interface directly. It will "ask" for that other interface.

This can be done in a very configurable manner using events and static events, which I am not going
to discuss in this article as it is already getting long, or it can be very simple, like having
a TryGetService<T>() in the main interface.

So, this is how a Stream could look if built of entirely of segregated interfaces:

Hide Shrink Copy Code

public interface IStream:


IDisposable
{
T TryGetService<T>();
}

public interface IReadStream:


IStream
{
// The partial methods may read less than the amount requested.
int PartialRead(byte[] buffer);
int PartialRead(byte[] buffer, int offset);
int PartialRead(byte[] buffer, int offset, int length);

// These methods will either read all the requested amount


// or throw an exception if the stream ends before that amount.
void Read(byte[] buffer);
void Read(byte[] buffer, int offset);
void Read(byte[] buffer, int offset, int length);
}

public interface IWriteStream:


IStream
{
// The partial methods may write less than the amount requested.
int PartialWrite(byte[] buffer);
int PartialWrite(byte[] buffer, int offset);
int PartialWrite(byte[] buffer, int offset, int length);

// These methods will either write all the requested amount


// or throw an exception if the stream is full before all
// the data was written.
void Write(byte[] buffer);
void Write(byte[] buffer, int offset);
void Write(byte[] buffer, int offset, int length);
}

// Maybe the size should be in another interface, but I consider


// that we should not be able to reposition to the end if we don't
// know the size of the stream, so I put both together.
public interface IReadPositionableStream:
IReadStream
{
long Position { get; }
long Size { get; }
}

public interface IWritePositionableStream:


IWriteStream
{
void SetPosition(long value);
void SetSize(long value);
}

public interface IReadTimeoutStream:


IReadStream
{
TimeSpan? ReadTimeout { get; set; }
}

public interface IWriteTimeoutStream:


IWriteStream
{
TimeSpan? WriteTimeout { get; set; }
}

With these interfaces, code that requires a read stream that supports timeouts may have an input
parameter of type IReadTimeoutStream.

A code that wants to write to a stream that may be repositioned may request for
an IWritePositionableStream directly, yet it may try to configure a timeout by requesting
the IWriteTimeoutStream.

During such request, a decorator may look if its inner stream supports that interface. If the inner
stream doesn't support it, it may return null to tell that it doesn't support the service, yet in its code
it may actually implement all those interfaces, redirecting to the inner stream when possible. It can
actually delegate the decoration to another object, so it doesn't need to implement all the interfaces,
it only needs to know how to find/create the other implementation.

So, an important thing to remember is:

If you want to use segregated interfaces, don't do direct casts. Ask if the object can do the extra
actions by calling a method that may return an object of the right interface or null. This will greatly
simplify decorations.

Multiple inheritance
When seeing comparisons between interfaces and abstract classes it is common to see arguments
that a class can implement many interfaces but can only inherit from one abstract class (talking
about .NET... C++ supports multiple inheritance). So it is common to say that interfaces are the way
to go if we want multiple inheritance in .NET.

Well, that's actually a terrible argument. Using an abstract class we have the benefits of having a
default implementation. For example, I use base classes that implement
the INotifyPropertyChanged interface and call the event accordingly. Considering there's
an INotifyPropertyChanging interface too, I would love to have the possibility to implement
both interfaces with a default implementation by inheriting from two base classes, one for each
interface, and this is the kind of inheritance that I would not like to expose (private inheritance, also
not available in .NET). I would like that users of my class only saw my class directly inheriting from
object and implementing the interfaces, yet I would not need to write that repetitive code for the
interfaces.

So, considering that we may want abstract classes because of their default implementation and
considering that interfaces can't have a default implementation, having the possibility to implement
many interfaces doesn't help achieve multiple inheritance at all, we will still need to provide an
implementation to all of them.

Finally, if we return to the previous topic, if frameworks "asked" for a service instead of doing direct
casts, we could very well live with classes that are limited to implement either one base class or one
interface, as any extra service could be discovered at run-time by doing the right call and by
receiving different instances that implement the other interfaces if needed.

In the end, the fact that our classes may implement many interfaces is a nice to have feature, not a
required one, and it may be a needed feature to be able to use already existing frameworks that use
casts to interfaces to search for features. Looking to the problem differently, those frameworks were
created that way only because there's the support for multiple interfaces. Maybe all the frameworks
would work better if multiple interface implementations were never supported.
Summing it up
Right things

 If you want to call an abstraction, call an interface, not an abstract class. That is, input parameters
should use the type of an interface;
 If you want to give a default implementations to an interface, create an abstract class that
implements it, independently on how many methods are kept as abstract;
 If you want to implement either an interface or an abstract class to be able to pass a parameter to a
method that expects for the interface, use the interface if you prefer to implement all the methods
and to have errors that force you to revalidate your implementation if in the future new methods are
added to the interface. Use the abstract class if you prefer to use default implementations,
independently if they exist today or if they may be added in the future.

Maybe some developers will consider the next item debatable, especially because I never saw a well-
known pattern talking about it but, to me, it is the right thing to do:

 If you are writing a framework that may ask for different services of an object, don't do cast, prefer
using a method or, even better, an event to ask for that. This allows for easier decoration (as an
object that implements a specific interface can still say that it doesn't support it because the
decorated object doesn't) and users of the framework would be able to give implementations of the
interface even to third-party created objects.

Debatable things

1. Use of small interfaces is better;


2. The Interface Segregation Principle makes the code more maintainable;
3. Use of big interfaces is better;
4. You should not create an interface when you can create an abstract class and keep all the methods
as virtual or abstract;
5. You should write interfaces in one assembly and their default implementations (if any) in another
one.

The first two points are based on the idea that we should not force users to implement big interfaces
if we are only interested in a small part of it, but such segregation may make it hard to know what
are all the possible methods that can be used or implemented and may cause some performance
loss when we do actually want to use the "extra" functionalities;

The third point goes in the opposite direction, making it clear that all the possibilities are available at
a single place, so users know all the methods they can decorate and call, without having to learn
anything about "helper" classes;

The fourth point tries to avoid duplications. If an abstract class can have all its methods
reimplemented, there's no need for an extra interface to tell the same (and this may actually make
things a little faster, as apparently the virtual dispatch of class methods is faster than the virtual
dispatch of interface methods). But aside from possible performance and multiple inheritance issues
(as you may need to use a base class for something else) this may create the wrong pattern, both
because you may forget and put fields or non-virtual methods on the class and because of the next
point;

The fifth point is related to how the interfaces are used. Code that needs to use an interface doesn't
care if the implementations used an abstract class as the base or not. Such code doesn't need to
reference any assembly aside the one with the interfaces. This allows to use completely different
implementations without having to load any code that will not be used. Unfortunately, when you
want to use the default implementation, you will need to reference two assemblies (the interface one
+ the default implementation).

Wrong thing

 You should always use interfaces. Abstract classes are bad because class inheritance is bad.

This point, well, I think that there are enough differences, each one has its strong points and they can
complement each other, so there's no need to choose one over the other in all situations.

The Sample
The sample application isn't useful as an application, being useful only as a "proof of concept".

Its purpose is to show how we can combine Interface Segregation Principle, Interfaces + Abstract
classes and decoration by "requesting services" instead of doing direct casts.

In fact, it has the IStream and its sub-interfaces presented in this article + abstract classes that
implement them and an adapter to redirect all the calls to a normal .NET Stream. If we were
seriously trying to recreate the Streams we should avoid redirecting to the .NET Stream, but this is
only a sample.

I believe this sample shows both the potential of this solution (as it can be expanded "without limits"
while keeping decoration possible) yet it shows the problem of segregated interfaces, as something
that could be done with a single abstract class + a single implementation is done through many
classes and interfaces, making it hard to figure out the direct utilisation or implementation. So, it
works both as a proof of the potential as well as a proof of the problems of these patterns.

Diamond Problem

Actually having a TryGetService<T> in the basic stream creates a kind of Diamond Problem,
considered a big problem of multiple inheritance. As the TryGetService<T> can return another
object, which also has a TryGetService<T>, such another object may have a different
implementation for it. This is simply an error, as every object returned should have the same
implementation for such method.
To solve this problem, in the sample I created the StreamPart abstract class. Each "part" of the
stream actually redirects to the main stream when the TryGetService<T> is invoked, so we can say
that they don't have their own implementation (or that they use the same implementation). If they
had their own implementation it would be very strange, as we could ask the main stream for a
service and get it, yet from that service itself such request could fail. All in all, this is a problem with
the architecture in which the objects may answer if they support a service or not by possibly giving
new objects but, as you can see, it can be solved by always redirecting to the "first" object.

Understanding SQL Injection and Creating


SQL Injection Proof ASP.NET Applications

Introduction
This article talk about what SQL injection is, how can that effect the security of our websites and
what steps should be taken to create an ASP.NET application SQL injection proof.

Background
As ASP.NET developers, we often write dynamic SQL to perform some database operations. These
dynamic SQLis some cases might be created by concatenating strings with user input. If we are not
validating the user input and taking every input as is, then this kind of scenario poses a very serious
problem of SQL injection.

SQL injection is the attack in which the user of the website will input some SQL code as input which
would result in creating a SQL statement that developers didn't intend to write.
These SQL statements could result in unauthorized access, revealing secret user information and
sometimes it could even wipe out the entire data lying on the server.

Using the code


Getting to know SQL Injection

Let us take this discussion a little further by looking into the bad coding practices that will make the
application prone to the SQL injection attacks. Let us create a simple table that contains username
and password of the user for authentication.
Now I will create a small page that lets the user to enter his login credentials and get them
validated against the Users table.

Note: Password should never be stored in plain text. This table contains password in plain text just
for the sake of simplicity of this article.

The actual code that I will use to authenticate the user contains dynamic SQL that is being created
by concatenating strings. This code will return true if the userid and password are found in the
database otherwise false.

Hide Shrink Copy Code

public bool IsUserAuthenticated_Bad(string username, string password)


{
DataTable result = null;
try
{
using (SqlConnection con = new
SqlConnection(ConfigurationManager.ConnectionStrings["SampleDbConnectionString1"].ConnectionSt
ring))
{
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select userID from Users where userID = '" + username + "'
and password = '" + password + "'";

using (SqlDataAdapter da = new SqlDataAdapter(cmd))


{
result = new DataTable();
da.Fill(result);

//check if any match is found


if (result.Rows.Count == 1)
{
// return true to indicate that userID and password are matched.
return true;
}
}
}
}
}
catch (Exception ex)
{
//Pokemon exception handling
}

//user id not found, lets treat him as a guest


return false;
}

For all the normal users this code will work fine. I can even test it
using userid as sampleuser and passwordas samplepwd and this will work fine. For any other
data except this it should say that authentication failed(since this is the only record in the table). The
query that will get generated to test this input will be:

Hide Copy Code

select userID from Users where userID = 'sampleuser' and password = 'samplepwd'

Now let us try to inject some SQL into this page. Let me give hacker' or 1=1--
as username and anything in the password(even leave it empty). Now the resultant SQL for this
will become:

Hide Copy Code

select userID from Users where userID = 'hacker' or 1=1--' and password = ''
Now when we execute this query the 1=1 clause will always return true(and the password check is
commented out. Now irrespective of whatever data user has entered this will SQL return a row
making this function return true and in turn authenticating the user. So What I have done now is that
I gained access to the website even when I didn't knew the valid user credentials.

How can I curb this problem is something we will look into details in some time. But before that let
us also look at one more example of SQL injection just to get little more understanding.

In this second example we will assume that the malicious user somehow got hold of the database
schema and then he is trying to manipulate the application to find some confidential information.
Lets say we have a page that is supposed to show all the products that are assigned to a user in the
organization.

Let us start by looking at the Product table.

Let us now look at the code that is retrieving this data:

Hide Shrink Copy Code


public DataTable GetProductsAssigner_Bad(string userID)
{
DataTable result = null;
try
{
using (SqlConnection con = new
SqlConnection(ConfigurationManager.ConnectionStrings["SampleDbConnectionString1"].ConnectionSt
ring))
{
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from Products where AssignedTo = '" + userID +
"'";

using (SqlDataAdapter da = new SqlDataAdapter(cmd))


{
result = new DataTable();
da.Fill(result);
}
}
}
}
catch (Exception ex)
{
//Pokemon exception handling
}

//user id not found, lets treat him as a guest


return result;
}

Now if I call this function with the proper data(as normal users would do) then this will show me the
results. i.e. If I call this page for sampleuser the resulting query would be:

Hide Copy Code

select * from Products where AssignedTo = 'sampleuser'


Now let me use this query string with this page: userID=' UNION SELECT 0 AS Expr1,
password, userID FROM Users -- . Once this data is used with the current code this will show
me all the username and passwords from the database. The reason will be quiet clear once we look
into the resulting query of this input.

Hide Copy Code

select * from Products where AssignedTo = '' UNION SELECT 0 AS Expr1, password, userID FROM
Users --

Now we saw that how string concatenated dynamic SQL is prone to SQL injection. There are many
other problems that could be created by injecting SQL. Imagine a scenario where the injected SQL is
dropping tables or truncating all the tables. The problem in such cases would be catastrophic.

How to Prevent SQL Injection

ASP.NET provides us beautiful mechanism for prevention against the SQL injection. There are some
thumb rules that should be followed in order to prevent injection attacks on our websites.

1. User input should never be trusted. It should always be validated


2. Dynamic SQL should never be created using string concatenations.
3. Always prefer using Stored Procedures.
4. If dynamic SQL is needed it should be used with parametrized commands.
5. All sensitive and confidential information should be stored in encrypted.
6. The application should never use/access the DB with Administrator privileges.

User input should never be trusted. It should always be validated

The basic thumb rule here is that the user input should never be trusted. First of all we should apply
filters on all the input fields. If any field is supposed to take numbers then we should never accept
alphabets in that. Secondly, All the inputs should be validated against a regular expression so that
no SQL characters and SQL command keywords are passed to the database.
Both this filtration and validation should be done at client side using JavaScript. It would suffice for
the normal user. Malicious users cans till bypass the client side validations. So to curb that all the
validations should be done at server side too.

Dynamic SQL should never be created using string concatenations.

If we have dynamic SQL being created using string concatenations then we are always at the risk of
getting some SQL that we are not supposed to use with the application. It is advisable to avoid the
string concatenations altogether.

Always prefer using Stored Procedures.

Stored procedures are the best way of performing the DB operations. We can always be sure of that
no bad SQLis being generated if we are using stored procedures. Let us create a Stored procedure
for the database access required for our login page and see what is the right way of doing the
database operation using stored procedure.

Hide Copy Code

CREATE PROCEDURE dbo.CheckUser


(
@userID varchar(20),
@password varchar(16)
)
AS
select userID from Users where userID = @userID and password = @password
RETURN

And now lets have a good version in our code using this stored procedure.

Hide Shrink Copy Code

public bool IsUserAuthenticated_Good(string username, string password)


{
DataTable result = null;
try
{
using (SqlConnection con = new
SqlConnection(ConfigurationManager.ConnectionStrings["SampleDbConnectionString1"].ConnectionSt
ring))
{
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "CheckUser";
cmd.Parameters.Add(new SqlParameter("@userID", username));
cmd.Parameters.Add(new SqlParameter("@password", password));

using (SqlDataAdapter da = new SqlDataAdapter(cmd))


{
result = new DataTable();
da.Fill(result);
//check if any match is found
if (result.Rows.Count == 1)
{
// return true to indicate that userID and password are matched.
return true;
}
}
}
}
}
catch (Exception ex)
{
//Pokemon exception handling
}

//user id not found, lets treat him as a guest


return false;
}

If dynamic SQL is needed it should be used with parametrized commands.

If we still find our self needing the dynamic SQL in code then parametrized commands are the best
way of performing such dynamic SQL business. This way we can always be sure of that no
bad SQL is being generated. Let us create a parametrized command for the database access
required for our Product page and see what is the right way of doing the database operation.

Hide Shrink Copy Code

public DataTable GetProductsAssigner_Good(string userID)


{
DataTable result = null;
try
{
using (SqlConnection con = new
SqlConnection(ConfigurationManager.ConnectionStrings["SampleDbConnectionString1"].ConnectionSt
ring))
{
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from Products where AssignedTo = @userID";
cmd.Parameters.Add(new SqlParameter("@userID", userID));

using (SqlDataAdapter da = new SqlDataAdapter(cmd))


{
result = new DataTable();
da.Fill(result);
}
}
}
}
catch (Exception ex)
{
//Pokemon exception handling
}
//user id not found, lets treat him as a guest
return result;
}

All sensitive and confidential information should be stored in encrypted.

All the sensitive information should be stored encrypted in the database. The benefit of having this is
that even if somehow the user get hold of the data he will only be able to see the encrypted values
which are not easy to use for someone who doesn't know the encryption technique used by the
application.

The application should never use/access the DB with Administrator privileges.

This will make sure that even if the bad SQL is being passed to the Database by some injections, the
database will not allow any catastrophic actions like dropping table.

Note: Refer the sample application attached to see the working examples SQL injection and how to
curb them using parametrized commands and stored procedures.

Point of interest
This is a very basic article on SQL injection. I have specifically focused on ASP.NET applications but
same concept will apply for any ADO.NET application. This article is meant for the beginner's who
know nothing or too little about SQL injection and making the applications SQL injection proof. I
hope this has been informative.

Implementation of Dependency Injection


Pattern in C#

pendency Injection (DI) is a software design pattern that allow us to develop loosely coupled code.
DI is a great way to reduce tight coupling between software components. DI also enables us to
better manage future changes and other complexity in our software. The purpose of DI is to make
code maintainable.
The Dependency Injection pattern uses a builder object to initialize objects and provide the required
dependencies to the object means it allows you to "inject" a dependency from outside the class.
For example, Suppose your Client class needs to use a Service class component, then the best you
can do is to make your Client class aware of an IService interface rather than a Service class. In
this way, you can change the implementation of the Service class at any time (and for how many
times you want) without breaking the host code.
We can modify this code by the DI different ways. We have following different ways to implement DI
:

Constructor Injection
1. This is the most common DI.
2. Dependency Injection is done by supplying the DEPENDENCY through the class’s constructor
when instantiating that class.
3. Injected component can be used anywhere within the class.
4. Should be used when the injected dependency is required for the class to function.
5. It addresses the most common scenario where a class requires one or more dependencies.

1. public interface IService


2. {
3. void Serve();
4. }
5.
6. public class Service : IService
7. {
8. public void Serve()
9. {
10. Console.WriteLine("Service Called");
11. //To Do: Some Stuff
12. }
13. }
14.
15. public class Client
16. {
17. private IService _service;
18.
19. public Client(IService service)
20. {
21. this._service = service;
22. }
23.
24. public void Start()
25. {
26. Console.WriteLine("Service Started");
27. this._service.Serve();
28. //To Do: Some Stuff
29. }
30. }
31. class Program
32. {
33. static void Main(string[] args)
34. {
35. Client client = new Client(new Service());
36. client.Start();
37.
38. Console.ReadKey();
39. }
40. }
The Injection happens in the constructor, by passing the Service that implements the IService-
Interface. The dependencies are assembled by a "Builder" and Builder responsibilities are as follows:
1. knowing the types of each IService
2. according to the request, feed the abstract IService to the Client

Property injection
1. Also called Setter injection.
2. Used when a class has optional dependencies, or where the implementations may need to be
swapped. Different logger implementations could be used this way.
3. May require checking for a provided implementation throughout the class(need to check for
null before using it).
4. Does not require adding or modifying constructors.
5.
1. public interface IService
2. {
3. void Serve();
4. }
5.
6. public class Service : IService
7. {
8. public void Serve()
9. {
10. Console.WriteLine("Service Called");
11. //To Do: Some Stuff
12. }
13. }
14.
15. public class Client
16. {
17. private IService _service;
18.
19. public IService Service
20. {
21. set
22. {
23. this._service = value;
24. }
25. }
26.
27. public void Start()
28. {
29. Console.WriteLine("Service Started");
30. this._service.Serve();
31. //To Do: Some Stuff
32. }
33. }
34. class Program
35. {
36. static void Main(string[] args)
37. {
38. Client client = new Client();
39. client.Service = new Service();
40. client.Start();
41.
42. Console.ReadKey();
43. }
44. }

Method injection
1. Inject the dependency into a single method, for use by that method.
2. Could be useful where the whole class does not need the dependency, just the one method.
3. Generally uncommon, usually used for edge cases.
1. public interface IService
2. {
3. void Serve();
4. }
5.
6. public class Service : IService
7. {
8. public void Serve()
9. {
10. Console.WriteLine("Service Called");
11. //To Do: Some Stuff
12. }
13. }
14.
15. public class Client
16. {
17. private IService _service;
18.
19. public void Start(IService service)
20. {
21. this._service = service;
22. Console.WriteLine("Service Started");
23. this._service.Serve();
24. //To Do: Some Stuff
25. }
26. }
27. class Program
28. {
29. static void Main(string[] args)
30. {
31. Client client = new Client();
32. client.Start(new Service());
33.
34. Console.ReadKey();
35. }
36. }

Key points about DI


1. Reduces class coupling
2. Increases code reusing
3. Improves code maintainability
4. Improves application testing

Constructors in C#
Constructor is a special method of a class which will invoke automatically whenever instance
or object of class is created. Constructors are responsible for object initialization and
memory allocation of its class. If we create any class without constructor, the compiler will
automatically create one default constructor for that class. There is always at least one
constructor in every class.

Here you need to remember that a class can have any number of constructors and
constructors don’t have any return type, not even void and within a class we can create only
one static constructor.

Generally constructor name should be same as class name. If we want to create constructor
in a class we need to create a constructor method name same as class name check below
sample method for constructor

class SampleA
{
public SampleA()
{
Console.WriteLine("Sample A Test Method");
}
}

Types of Constructors

Basically constructors are 5 types those are

1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor
4. Static Constructor
5. Private Constructor

Default Constructor

A constructor without having any parameters called default constructor. In this constructor
every instance of the class will be initialized without any parameter values like as shown
below

using System;
namespace ConsoleApplication3
{
class Sample
{
public string param1, param2;
public Sample() // Default Constructor
{
param1 = "Welcome";
param2 = "Aspdotnet-Suresh";
}
}
class Program
{
static void Main(string[] args)
{
Sample obj=new Sample(); // Once object of class created automatically constructor will be called
Console.WriteLine(obj.param1);
Console.WriteLine(obj.param2);
Console.ReadLine();
}
}
}
When we run above program it will show output like as shown below

Output

Welcome
Aspdotnet-Suresh

Parameterized Constructors

A constructor with at least one parameter is called as parameterized constructor. In


parameterized constructor we can initialize each instance of the class to different values like
as shown below

using System;
namespace ConsoleApplication3
{
class Sample
{
public string param1, param2;
public Sample(string x, string y) // Declaring Parameterized constructor with Parameters
{
param1 = x;
param2 = y;
}
}
class Program
{
static void Main(string[] args)
{
Sample obj=new Sample("Welcome","Aspdotnet-Suresh"); // Parameterized Constructor Called
Console.WriteLine(obj.param1 +" to "+ obj.param2);
Console.ReadLine();
}
}
}
When we run above program it will show output like as shown below

Output

Welcome to Aspdotnet-Suresh

Constructor Overloading

In c# we can overload constructor by creating another constructor with same method name
and different parameters like as shown below

using System;
namespace ConsoleApplication3
{
class Sample
{
public string param1, param2;

public Sample() // Default Constructor


{
param1 = "Hi";
param2 = "I am Default Constructor";
}
public Sample(string x, string y) // Declaring Parameterized constructor with Parameters
{
param1 = x;
param2 = y;
}
}
class Program
{
static void Main(string[] args)
{
Sample obj = new Sample(); // Default Constructor will Called
Sample obj1=new Sample("Welcome","Aspdotnet-Suresh"); // Parameterized Constructor will Called
Console.WriteLine(obj.param1 + ", "+obj.param2);
Console.WriteLine(obj1.param1 +" to " + obj1.param2);
Console.ReadLine();
}
}
When we run above program it will show output like as shown below

Output

Hi, I am Default Constructor


Welcome to Aspdotnet-Suresh

Copy Constructor

A parameterized constructor that contains a parameter of same class type is called as copy
constructor. Main purpose of copy constructor is to initialize new instance to the values of
an existing instance. Check below example for this

using System;
namespace ConsoleApplication3
{
class Sample
{
public string param1, param2;
public Sample(string x, string y)
{
param1 = x;
param2 = y;
}
public Sample(Sample obj) // Copy Constructor
{
param1 = obj.param1;
param2 = obj.param2;
}
}
class Program
{
static void Main(string[] args)
{
Sample obj = new Sample("Welcome", "Aspdotnet-Suresh"); // Create instance to class Sample
Sample obj1=new Sample(obj); // Here obj details will copied to obj1
Console.WriteLine(obj1.param1 +" to " + obj1.param2);
Console.ReadLine();
}
}
}
When we run above program it will show output like as shown below

Output

Welcome to Aspdotnet-Suresh

Static Constructor

When we declared constructor as static it will be invoked only once for any number of
instances of the class and it’s during the creation of first instance of the class or the first
reference to a static member in the class. Static constructor is used to initialize static fields
of the class and to write the code that needs to be executed only once.

using System;
namespace ConsoleApplication3
{
class Sample
{
public string param1, param2;
static Sample()
{
Console.WriteLine("Static Constructor");
}
public Sample()
{
param1 = "Sample";
param2 = "Instance Constructor";
}
}
class Program
{
static void Main(string[] args)
{
// Here Both Static and instance constructors are invoked for first instance
Sample obj=new Sample();
Console.WriteLine(obj.param1 + " " + obj.param2);
// Here only instance constructor will be invoked
Sample obj1 = new Sample();
Console.WriteLine(obj1.param1 +" " + obj1.param2);
Console.ReadLine();
}
}
}
When we run above program we will get output like as shown below

Output

Static Constructor
Sample Instance Constructor
Sample Instance Constructor
Importance points of static constructor

- Static constructor will not accept any parameters because it is automatically called by CLR.
- Static constructor will not have any access modifiers.
- Static constructor will execute automatically whenever we create first instance of class
- Only one static constructor will allowed.

Private Constructor

Private constructor is a special instance constructor used in a class that contains static
member only. If a class has one or more private constructor and no public constructor then
other classes is not allowed to create instance of this class this mean we can neither create
the object of the class nor it can be inherit by other class. The main purpose of creating
private constructor is used to restrict the class from being instantiated when it contains
every member as static.

using System;
namespace ConsoleApplication3
{
public class Sample
{
public string param1, param2;
public Sample(string a,string b)
{
param1 = a;
param2 = b;
}
private Sample() // Private Constructor Declaration
{
Console.WriteLine("Private Constructor with no prameters");
}
}
class Program
{
static void Main(string[] args)
{
// Here we don't have chance to create instace for private constructor
Sample obj = new Sample("Welcome","to Aspdotnet-Suresh");
Console.WriteLine(obj.param1 +" " + obj.param2);
Console.ReadLine();
}
}
}

Output

Welcome to Aspdotnet-Suresh

In above method we can create object of class with parameters will work fine. If create
object of class without parameters it will not allow us create.

// it will works fine


Sample obj = new Sample("Welcome","to Aspdotnet-Suresh");
// it will not work because of inaccessability
Sample obj=new Sample();
Important points of private constructor

- One use of private construct is when we have only static member.


- Once we provide a constructor that is either private or public or any, the compiler will not
allow us to add public constructor without parameters to the class.
- If we want to create object of class even if we have private constructors then we need to
have public constructor along with private constructor

Understand Lambda Expressions

Introduction
A lambda expression is an anonymous function and it is mostly used to create delegates in LINQ.
Simply put, it's a method without a declaration, i.e., access modifier, return value declaration, and
name.

Convenience. It's a shorthand that allows you to write a method in the same place you are going to
use it. Especially useful in places where a method is being used only once, and the method definition
is short. It saves you the effort of declaring and writing a separate method to the containing class.

Benefits

Lambda expressions should be short. A complex definition makes the calling code difficult to read.

Lambda basic definition: Parameters => Executed code

1. What is a Lambda Expression?


2. Why do we need lambda expressions? (Why would we need to write a method without a name?)
1. Reduced typing. No need to specify the name of the function, its return type, and its access modifier.
2. When reading the code, you don't need to look elsewhere for the method's definition.
3. How do we define a lambda expression?

Simple Example
Hide Copy Code

n => n % 2 == 1

 n is the input parameter


 n % 2 == 1 is the expression

You can read n => n % 2 == 1 like: "input parameter named n goes to anonymous function which
returns true if the input is odd".

Same example (now execute the lambda):

Hide Copy Code

List<int> numbers = new List<int>{11,37,52};


List<int> oddNumbers = numbers.where(n => n % 2 == 1).ToList();
//Now oddNumbers is equal to 11 and 37

That's all, now you know the basics of Lambda Expressions.

 I didn't mention expression trees/run time advantages of lambda expression due to limited scope.

Difference Between Finalize and Dispose


Method

Difference between Dispose & Finalize Method

Dispose

Finalize

It is used to free unmanaged resources like files, database connections etc. at any time.

It can be used to free unmanaged resources (when you implement it) like files, database connections
etc. held by an object before that object is destroyed.

Explicitly, it is called by user code and the class which is implementing dispose method, must has to
implement IDisposable interface.
Internally, it is called by Garbage Collector and cannot be called by user code.

It belongs to IDisposable interface.

It belongs to Object class.

It's implemented by implementing IDisposable interface Dispose() method.

It's implemented with the help of destructor in C++ & C#.

There is no performance costs associated with Dispose method.

There is performance costs associated with Finalize method since it doesn't clean the memory
immediately and called by GC automatically.

Example for implementing the dispose method


1. public class MyClass : IDisposable
2. {
3. private bool disposed = false;
4.
5. //Implement IDisposable.
6. public void Dispose()
7. {
8. Dispose(true);
9. GC.SuppressFinalize(this);
10. }
11.
12. protected virtual void Dispose(bool disposing)
13. {
14. if (!disposed)
15. {
16. if (disposing)
17. {
18. // TO DO: clean up managed objects
19. }
20.
21. // TO DO: clean up unmanaged objects
22.
23. disposed = true;
24. }
25. }
26. }

Example for implementing Finalize method


If you want to implement Finalize method, it is recommended to use Finalize and Dispose method
together as shown below:
1. // Using Dispose and Finalize method together
2. public class MyClass : IDisposable
3. {
4. private bool disposed = false;
5.
6. //Implement IDisposable.
7. public void Dispose()
8. {
9. Dispose(true);
10. GC.SuppressFinalize(this);
11. }
12.
13. protected virtual void Dispose(bool disposing)
14. {
15. if (!disposed)
16. {
17. if (disposing)
18. {
19. // TO DO: clean up managed objects
20. }
21.
22. // TO DO: clean up unmanaged objects
23.
24. disposed = true;
25. }
26. }
27.
28. //At runtime C# destructor is automatically Converted to Finalize method
29. ~MyClass()
30. {
31. Dispose(false);
32. }
33. }

Note
1. It is always recommended to use Dispose method to clean unmanaged resources. You should not
implement the Finalize method until it is extremely necessary.
2. At runtime C#, C++ destructors are automatically Converted to Finalize method. But in VB.NET you
need to override Finalize method, since it does not support destructor.
3. You should not implement a Finalize method for managed objects, because the garbage collector
cleans up managed resources automatically.
4. A Dispose method should call the GC.SuppressFinalize() method for the object of a class which has
destructor because it has already done the work to clean up the object, then it is not necessary for
the garbage collector to call the object's Finalize method.

Difference between CTE and Temp Table and


Table Variable
CTE
CTE stands for Common Table expressions. It was introduced with SQL Server 2005. It is a temporary
result set and typically it may be a result of complex sub-query. Unlike temporary table its life is
limited to the current query. It is defined by using WITH statement. CTE improves readability and
ease in maintenance of complex queries and sub-queries. Always begin CTE with semicolon.

A sub query without CTE is given below :


1. SELECT * FROM (
2. SELECT Addr.Address, Emp.Name, Emp.Age From Address Addr
3. Inner join Employee Emp on Emp.EID = Addr.EID) Temp
4. WHERE Temp.Age > 50
5. ORDER BY Temp.NAME

By using CTE above query can be re-written as follows :


1. ;With CTE1(Address, Name, Age)--Column names for CTE, which are optional
2. AS
3. (
4. SELECT Addr.Address, Emp.Name, Emp.Age from Address Addr
5. INNER JOIN EMP Emp ON Emp.EID = Addr.EID
6. )
7. SELECT * FROM CTE1 --Using CTE
8. WHERE CTE1.Age > 50
9. ORDER BY CTE1.NAME

When to use CTE


1. This is used to store result of a complex sub query for further use.
2. This is also used to create a recursive query.

Temporary Tables
In SQL Server, temporary tables are created at run-time and you can do all the operations which you
can do on a normal table. These tables are created inside Tempdb database. Based on the scope and
behavior temporary tables are of two types as given below-
1. Local Temp Table
Local temp tables are only available to the SQL Server session or connection (means single user)
that created the tables. These are automatically deleted when the session that created the
tables has been closed. Local temporary table name is stared with single hash ("#") sign.
1. CREATE TABLE #LocalTemp
2. (
3. UserID int,
4. Name varchar(50),
5. Address varchar(150)
6. )
7. GO
8. insert into #LocalTemp values ( 1, 'Shailendra','Noida');
9. GO
10. Select * from #LocalTemp
The scope of Local temp table exist to the current session of current user means to the current
query window. If you will close the current query window or open a new query window and will
try to find above created temp table, it will give you the error.
2. Global Temp Table
Global temp tables are available to all SQL Server sessions or connections (means all the user).
These can be created by any SQL Server connection user and these are automatically deleted
when all the SQL Server connections have been closed. Global temporary table name is stared
with double hash ("##") sign.
1. CREATE TABLE ##GlobalTemp
2. (
3. UserID int,
4. Name varchar(50),
5. Address varchar(150)
6. )
7. GO
8. insert into ##GlobalTemp values ( 1, 'Shailendra','Noida');
9. GO
10. Select * from ##GlobalTemp
11.

Global temporary tables are visible to all SQL Server connections while Local temporary tables
are visible to only current SQL Server connection.

Table Variable
This acts like a variable and exists for a particular batch of query execution. It gets dropped once it
comes out of batch. This is also created in the Tempdb database but not the memory. This also
allows you to create primary key, identity at the time of Table variable declaration but not non-
clustered index.
1. GO
2. DECLARE @TProduct TABLE
3. (
4. SNo INT IDENTITY(1,1),
5. ProductID INT,
6. Qty INT
7. )
8. --Insert data to Table variable @Product
9. INSERT INTO @TProduct(ProductID,Qty)
10. SELECT DISTINCT ProductID, Qty FROM ProductsSales ORDER BY ProductID ASC
11. --Select data
12. Select * from @TProduct
13.
14. --Next batch
15. GO
16. Select * from @TProduct --gives error in next batch
17.

Note
1. Temp Tables are physically created in the Tempdb database. These tables act as the normal table
and also can have constraints, index like normal tables.
2. CTE is a named temporary result set which is used to manipulate the complex sub-queries data. This
exists for the scope of statement. This is created in memory rather than Tempdb database. You
cannot create any index on CTE.
3. Table Variable acts like a variable and exists for a particular batch of query execution. It gets
dropped once it comes out of batch. This is also created in the Tempdb database but not the
memory.

Generic Types in C# 2.0 with Sample


Introduction

Generics procedure many of the benefits of strongly-typed collections as well as provide a higher quality
of and a performance boost for code. Generics are very similar to C++ templates but having a slight
difference in such a way that the source code of C++ templates is required when a templates is
instantiated with a specific type and .NET Generics are not limited to classes only. In fact they can also be
implemented with Interfaces, Delegates and Methods. The detailed specification for each collection is
found under the System.Collection.Generic namespace.

Boxing and Unboxing

.Net defines two major categories of data type termed value type and reference type to represent a
variable. This is where boxing and unboxing are needed. Boxing is a mechanism to explicitly convert a
value type to a reference type by storing the variable into System.Object; when you box the value the CLR
allocates a new object into the heap and copies the value type's value into that instance. For example you
have created a variable of int type as:

int a = 20;
object b = a; //boxing

The opposite operation is Unboxing which is the process of converting back the reference type into the
value type. This process verifies that the receiving data type is equivalent to the boxed type as;

int c = (int)b; // unboxing


The C# compiler sees the assignment from int to object and vice-versa. When this program is compiled
and you examine the IL generated code via IL dissembler, you notice that the program respond by
inserting a box instruction in the IL automatically when b is assigned the value of a and an unbox
instruction when c is assigned the value b as in the following;

Figure 1.1 - IL opcode

The code loads the constant 20 and stores it in the local slot; it the loads the value 20 onto the stack and
boxes it. Finally it loads the boxed 20 back onto the stack and unboxes it into an int.

There are series of operations performed by .NET CLR, such as, first an object is allocated in the managed
heap, then in boxing the value is transformed into the memory location and during unboxing the value is
stored on the heap and must be transferred back to the stack. So the Boxing and Unboxing process has a
significant importance in Generics from the performance point of view because this process is more
resource-intensive rather than using Generics.

Generic Classes

The Generic class can be defined by putting the <T> sign after the class name. It isn't mandatory to put
the "T" word in the Generic type definition. You can use any word in the TestClass<> class declaration.

public class TestClass<T> { }

The System.Collection.Generic namespace also defines a number of classes that implement many of these
key interfaces. The following table describes the core class types of this namespace.

Non-Generics Members Description


The basis for a generic collection Comparer compares two generic
Collection<T>
objects for equality
Dictionary<TKey,
A generic collection of name/value pairs
TValue>
List<T> A dynamically resizable list of Items
Queue<T> A generic implementation of a first-in, first-out (FIFO) list
Stack<T> A generic implementation of a last-in, first-out (LIFO) list

Simple Generic Class Example

The following example shows a simple Generic type manipulation. The TestClass<T> defines an array of
generic type with length 5. The Add() method is responsible for adding any type of objects into the
collection and the Indexer property is an implementation of foreach statement iteration. Finally in the
main class we instantiated the TestClass<T> class with an Integer type reference and adds some integer
type elements into the collection using the Add() method.

using System;
using System.Collections.Generic;

namespace GenericApp
{
public class TestClass<T>
{
// define an Array of Generic type with length 5
T[] obj = new T[5];
int count = 0;

// adding items mechanism into generic type


public void Add(T item)
{
//checking length
if (count + 1 < 6)
{
obj[count] = item;

}
count++;
}
//indexer for foreach statement iteration
public T this[int index]
{
get { return obj[index]; }
set { obj[index] = value; }
}
}
class Program
{
static void Main(string[] args)
{
//instantiate generic with Integer
TestClass<int> intObj = new TestClass<int>();
//adding integer values into collection
intObj.Add(1);
intObj.Add(2);
intObj.Add(3); //No boxing
intObj.Add(4);
intObj.Add(5);

//displaying values
for (int i = 0; i < 5; i++)
{
Console.WriteLine(intObj[i]); //No unboxing
}
Console.ReadKey();
}
}
}

After building and running this program, the output of the program is as shown in the following;

Figure 1.2 - Simple Generic Example

There are some significant characteristics of Generic types that make them special to the conventional
non-generics type as follows;

 Type Safety

 Performance

 Binary Code reuse

Type Safety

One of the most significant features of Generics is Type Safety. In the case of the non-generic ArrayList
class, if objects are used, any type can be added to the collections that can sometimes result in a great
disaster. The following example shows adding an integer, string and object to the collection of an
ArrayList type;

ArrayList obj = new ArrayList();


obj.Add(50);
obj.Add("Dog");
obj.Add(new TestClass());

Now, if the collection is iterated through the foreach statement using integer elements, the compiler
accepts the code but because all the elements in the collection are not an integer, a runtime exception
occurs;

foreach(int i in obj)
{
Console.WriteLine(i);
}

The rule of thumb in programming is that Errors should be detected as early as possible. With the generic
class Test<T>, the generic type T defines what types are allowed. With the definition of Test<int>, only an
integer type can be added to the collection. The compiler doesn't compile the code because the Add()
method has invalid arguments as follows;

Test<int> obj = new Test<int>();


obj.Add(50);
obj.Add("Dog"); //compiler error
obj.Add(new TestClass()); //compiler error

Performance

Another feature of Generics is performance. Using value types with non-generic collection classes result in
boxing and unboxing overhead when a value type is converted to reference type and vice-versa.

In the following example, the ArrayList class stores objects and the Add() method is defined to store some
integer type argument. So an integer type is boxed. When the value from ArrayList is read using the
foreach statement, unboxing occurrs.

ArrayList obj = new ArrayList();

obj.Add(50); //boxing- convert value type to reference type


int x= (int)obj[0]; //unboxing

foreach(int i in obj)
{
Console.WriteLine(i); // unboxing
}

Note: Generics are faster than other collections such as ArrayList.

Instead of using objects, a Generics type of the TestClass<T> class is defined as an int, so an int type is
used inside the class that is generated dynamically from the compiler. Therefore boxing and unboxing no
longer occurs as in the following;

TestClass<int> obj = new TestClass<int>();


obj.Add(50); //No boxing
int x= obj[0]; // No unboxing

foreach(int i in obj)
{
Console.WriteLine(i); //No unboxing
}

Binary Code reuse

Generics provide a kind of source code protection. A Generic class can be defined once and can be
instantiated with many different types. Generics can be defined in one CLR supported language and used
from another .NET language. The following TestClass<T> is instantiated with an int and string types:

TestClass<int> obj = new TestClass<int>();


obj.Add(50);

TestClass<string> obj1 = new TestClass<string>();


Obj1.Add("hello");

Generic Methods

While most developers will typically use the existing generic types within the base class libraries, it is
certainly possible to build your own generic members and custom generic types.

The objective of this example is to build a swap method that can operate on any possible data type
(value-based or reference-based) using a single type parameter. Due to the nature of swapping
algorithms, the incoming parameters will be sent by reference via ref keyword.

using System;
using System.Collections.Generic;
namespace GenericApp
{
class Program
{
//Generic method
static void Swap<T>(ref T a, ref T b)
{
T temp;
temp = a;
a = b;
b = temp;
}
static void Main(string[] args)
{
// Swap of two integers.
int a = 40, b = 60;
Console.WriteLine("Before swap: {0}, {1}", a, b);

Swap<int>(ref a, ref b);

Console.WriteLine("After swap: {0}, {1}", a, b);

Console.ReadLine();
}
}
}
After compiling this Generic method implementation program, the output is as in the following;

Figure 1.3 - Generic Methods

Dictionary

Dictionaries are also known as maps or hash tables. It represents a data structure that allows you to access
an element based on a key. One of the significant features of a dictionary is faster lookup; you can add or
remove items without the performance overhead.

.Net offers several dictionary classes, for instance Dictionary<TKey, TValue>. The type parameters TKey
and TValue represent the types of the keys and the values it can store, respectively.

Simple Example of Dictionary

The following example demonstrates simple dictionary collections using Generics. In this program, a
Dictionary type object is created that accepts an int as the key and a string as the value. Then we add
some string values into the dictionary collection and finally displaying the dictionary collection elements.

Using System;
using System.Collections.Generic;

namespace GenericApp
{
public class Program
{
static void Main(string[] args)
{
//define Dictionary collection
Dictionary<int,string> dObj = new Dictionary<int,string>(5);

//add elements to Dictionary

dObj.Add(1,1,"Tom");
dObj.Add(2,"John");
dObj.Add(3, "Maria");
dObj.Add(4, "Max");
dObj.Add(5, "Ram");

//print data
for (int i = 1; i <= dObj.Count;i++)
{
Console.WriteLine(dObj[i]);
}
Console.ReadKey();
}
}
}

The following example portrays some more complexities by defining an addition class emp where we are
overriding the ToString() method to display the name and salary of a particular employees. Later in the
Main() method , a new Dictionary<TKey,TValue) instance is created, where the key is of type string and the
value is of type emp. The constructor allocates a capacity of 2 elements. The emp objects and string value
as a key is added to the dictionary collection. Finally the collection elements are iterated using a foreach
statement and displayed on the screen.

using System;
using System.Text;
using System.Collections.Generic;

namespace GenericApp
{
public class emp
{
private string name;
private int salary;

public emp(string name,int salary)


{
this.name = name;
this.salary = salary;
}
public override string ToString()
{
StringBuilder sb = new StringBuilder(200);
sb.AppendFormat("{0},{1}",name,salary);

return sb.ToString();
}

}
public class Program
{
static void Main(string[] args)
{
//define Dictionary collection
Dictionary<string, emp> dObj = new Dictionary<string, emp>(2);

//add elements to Dictionary


emp tom = new emp("tom", 2000);
dObj.Add("tom",tom); // key,value
emp john = new emp("john", 4000);
dObj.Add("john",john);
//print data
foreach(Object str in dObj.Values)
{
Console.WriteLine(str);
}

Console.ReadKey();
}
}
}

Queues

Queues are a special type of container that ensures the items are being accessed in a FIFO (first in, first
out) manner. Queue collections are most appropriate for implementing messaging components. We can
define a Queue collection object using the following syntax:

Queue qObj = new Queue();

The Queue collection property, methods and other specification definitions are found under the
Sysyem.Collection namespace. The following table defines the key members;

System.Collection.Queue Members Definition


Enqueue() Add an object to the end of the queue.
Dequeue() Removes an object from the beginning of the queue.
Peek() Return the object at the beginning of the queue without removing it.

The following demonstrates a basic Queues type collection, adds some string type values into the
collection and finally displays the entire items into the collection using the while statement.

Using System;
using System.Collections;

namespace GenericApp
{
class Program
{
static void Main(string[] args)
{
//Defines a Queue.
Queue qObj = new Queue();

//adding string values into collection


qObj.Enqueue("Tom");
qObj.Enqueue("Harry");
qObj.Enqueue("Maria");
qObj.Enqueue("john");

//displaying collections
while(qObj.Count !=0 )
{
Console.WriteLine(qObj.Dequeue());
}

Console.ReadKey();
}
}
}

Stacks

A Stack collection is an abstraction of LIFO (last in, first out). We can define a Stack collection object using
the following syntax:

Stack qObj = new Stack();

The following table illustrates the key members of a stack;

System.Collection.Stack Members Definition


Contains() Returns true if a specific element is found in the collection.
Clear() Removes all the elements of the collection.
Peek() Previews the most recent element on the stack.
Push() It pushes elements onto the stack.
Pop() Return and remove the top elements of the stack.

The following demonstrate a stack collection. First an array type object is referenced into the stack
collection. Then the value of the elements in the collection are removed from the stack using the Pop()
method and displayed on the screen.

using System;
using System.Collections;

namespace GenericApp
{
class Program
{
static void Main(string[] args)
{
int[] iArray = new int[] {1,2,3,4,5,6,7,8,9,10 };

//Define a stack
Stack sObj = new Stack(iArray);

Console.WriteLine("Total items="+sObj.Count);

//displaying collections
for (int i = 0; i < sObj.Count;++i )
{
Console.WriteLine(sObj.Pop());
}

Console.ReadKey();
}
}
}

In another example with a Generic implementation, 5 items are added to the stack with the Push()
method. With the foreach statement, all the items are iterated using the IEnumerable interface. The
enumerator of the stack does not remove the items; it just returns each item in a LIFO manner as in the
following:

using System;
using System.Collections.Generic;

namespace GenericApp
{
public class Program
{
static void Main(string[] args)
{
//define Dictionary collection
Dictionary<int,string> dObj = new Dictionary<int,string>(5);

//add elements to Dictionary


dObj.Add(1,"Tom");
dObj.Add(2,"John");
dObj.Add(3, "Maria");
dObj.Add(4, "Max");
dObj.Add(5, "Ram");

//print data
foreach(string i in dObj.Values)
{
Console.WriteLine(i);
}
Console.ReadKey();
}
}
}
What is the Difference between ArrayList
and List Class

Background
This is one of my favorite interview questions. This question helps me to find out if candidate has
good knowledge of generics or not. On the internet, there are a number of writeups on "difference
between Arrayand ArrayList" but I didn't find any on "difference
between ArrayList and List", so I am posting one...

Must Know
First, one should know what is upcasting? Upcasting is converting derived type into base type. In
.NET, all data-types are derived from Object. So we can typecast any type to Object type. For
example, if Customer is class, then we can create object of Customer like this:

Hide Copy Code

Object cust = new Customer()

Here new Customer() will create object on heap and its address we are putting in reference
variable of type Object.

ArrayList
Hide Copy Code

ArrayList marks = new ArrayList();


marks.Add(50);
marks.Add(70.5);
marks.Add("Sixty");
In the above code snippet, we are creating object of ArrayList and adding different type of data
in it. But actually ArrayList is a collection of Object type, and when we add
any item to ArrayList, it first converts it to object type (upcasting) and then adds it to collection
object.

Interesting Fact: As ArrayList can only create collection for Object type, it is said to be non-
generic class. It might be confusing as it seems that we can add any datatype value
like int, float, string to ArrayListcollection so in that sense it should be called as generic
class. But in fact, it internally converts all these datatypes in object type and then adds to
collection.

We can visualise it as:

List
Hide Copy Code

List<int> marks = new List<int>();

marks.Add(50);
marks.Add(70);
marks.Add(60);

In the above snippet, we can observe that while creating object of list class, we have
mentioned datatype of collection we want to create. We need to pass datatype while creating
object as List class doesn’t hard code it internally. So the above declaration will create marks as
collection of integers; and not collection of objects as in case of ArrayList.

We can visualize it as:


Interesting fact: In the above collection “marks” you can only add integers and no other type. In
that sense, it should be referred to as non-generic! But wait, using the same List class, you can also
create collection of string type:

Hide Copy Code

List<string> names = new List<string>();

Or even you can create collection of custom types. For example, collection of Student type can be
created as:

Hide Copy Code

List<Student> students = new List<Student>();

And as using same List class, now you are able to create collection of any data-type as integers,
strings or students; this class is known as Generic class.

One of the benefits of using generic collection is no need of boxing and unboxing while tackling with
collections of value types.

We can visualise List of string type (or any ref type) as:
Difference between Dispose & Finalize Method

Difference between Dispose & Finalize Method

Dispose

Finalize

It is used to free unmanaged resources like files, database connections etc. at any time.

It can be used to free unmanaged resources (when you implement it) like files, database connections
etc. held by an object before that object is destroyed.

Explicitly, it is called by user code and the class which is implementing dispose method, must has to
implement IDisposable interface.

Internally, it is called by Garbage Collector and cannot be called by user code.

It belongs to IDisposable interface.

It belongs to Object class.

It's implemented by implementing IDisposable interface Dispose() method.

It's implemented with the help of destructor in C++ & C#.

There is no performance costs associated with Dispose method.

There is performance costs associated with Finalize method since it doesn't clean the memory
immediately and called by GC automatically.

Example for implementing the dispose method


1. public class MyClass : IDisposable
2. {
3. private bool disposed = false;
4.
5. //Implement IDisposable.
6. public void Dispose()
7. {
8. Dispose(true);
9. GC.SuppressFinalize(this);
10. }
11.
12. protected virtual void Dispose(bool disposing)
13. {
14. if (!disposed)
15. {
16. if (disposing)
17. {
18. // TO DO: clean up managed objects
19. }
20.
21. // TO DO: clean up unmanaged objects
22.
23. disposed = true;
24. }
25. }
26. }

Example for implementing Finalize method


If you want to implement Finalize method, it is recommended to use Finalize and Dispose method
together as shown below:
1. // Using Dispose and Finalize method together
2. public class MyClass : IDisposable
3. {
4. private bool disposed = false;
5.
6. //Implement IDisposable.
7. public void Dispose()
8. {
9. Dispose(true);
10. GC.SuppressFinalize(this);
11. }
12.
13. protected virtual void Dispose(bool disposing)
14. {
15. if (!disposed)
16. {
17. if (disposing)
18. {
19. // TO DO: clean up managed objects
20. }
21.
22. // TO DO: clean up unmanaged objects
23.
24. disposed = true;
25. }
26. }
27.
28. //At runtime C# destructor is automatically Converted to Finalize method
29. ~MyClass()
30. {
31. Dispose(false);
32. }
33. }

Note
1. It is always recommended to use Dispose method to clean unmanaged resources. You should not
implement the Finalize method until it is extremely necessary.
2. At runtime C#, C++ destructors are automatically Converted to Finalize method. But in VB.NET you
need to override Finalize method, since it does not support destructor.
3. You should not implement a Finalize method for managed objects, because the garbage collector
cleans up managed resources automatically.
4. A Dispose method should call the GC.SuppressFinalize() method for the object of a class which has
destructor because it has already done the work to clean up the object, then it is not necessary for
the garbage collector to call the object's Finalize method.

What is the difference between a class and a structure?

Class:

1. A class is a reference type.


2. While instantiating a class, CLR allocates memory for its instance in heap.
3. Classes support inheritance.
4. Variables of a class can be assigned as null.
5. Class can contain constructor/destructor.

Structure:

1. A structure is a value type.


2. In structure, memory is allocated on stack.
3. Structures do not support inheritance.
4. Structure members cannot have null values.
5. Structure does not require constructor/destructor and members can be initialiazed automatically.
Difference between WCF and Web API and
WCF REST and Web Service

Web Service
1. It is based on SOAP and return data in XML form.
2. It support only HTTP protocol.
3. It is not open source but can be consumed by any client that understands xml.
4. It can be hosted only on IIS.

WCF
1. It is also based on SOAP and return data in XML form.
2. It is the evolution of the web service(ASMX) and support various protocols like TCP, HTTP,
HTTPS, Named Pipes, MSMQ.
3. The main issue with WCF is, its tedious and extensive configuration.
4. It is not open source but can be consumed by any client that understands xml.
5. It can be hosted with in the applicaion or on IIS or using window service.

WCF Rest
1. To use WCF as WCF Rest service you have to enable webHttpBindings.
2. It support HTTP GET and POST verbs by [WebGet] and [WebInvoke] attributes respectively.
3. To enable other HTTP verbs you have to do some configuration in IIS to accept request of that
particular verb on .svc files
4. Passing data through parameters using a WebGet needs configuration. The UriTemplate must
be specified
5. It support XML, JSON and ATOM data format.

Web API
1. This is the new framework for building HTTP services with easy and simple way.
2. Web API is open source an ideal platform for building REST-ful services over the .NET
Framework.
3. Unlike WCF Rest service, it use the full featues of HTTP (like URIs, request/response headers,
caching, versioning, various content formats)
4. It also supports the MVC features such as routing, controllers, action results, filter, model
binders, IOC container or dependency injection, unit testing that makes it more simple and
robust.
5. It can be hosted with in the application or on IIS.
6. It is light weight architecture and good for devices which have limited bandwidth like smart
phones.
7. Responses are formatted by Web API’s MediaTypeFormatter into JSON, XML or whatever
format you want to add as a MediaTypeFormatter.

To whom choose between WCF or WEB API


1. Choose WCF when you want to create a service that should support special scenarios such as
one way messaging, message queues, duplex communication etc.
2. Choose WCF when you want to create a service that can use fast transport channels when
available, such as TCP, Named Pipes, or maybe even UDP (in WCF 4.5), and you also want to
support HTTP when all other transport channels are unavailable.
3. Choose Web API when you want to create a resource-oriented services over HTTP that can use
the full features of HTTP (like URIs, request/response headers, caching, versioning, various
content formats).
4. Choose Web API when you want to expose your service to a broad range of clients including
browsers, mobiles, iphone and tablets.

Key points about data submitted by using HttpGet


1. GET - Requests data from a specified resource
2. An hyperlink or anchor tag that points to an action will ALWAYS be an HttpGet.
3. Data is submitted as a part of url.
4. Data is visible to the user as it posts as query string.
5. It is not secure but fast and quick.
6. It use Stack method for passing form variable.
7. Data is limited to max length of query string.
8. It is good when you want user to bookmark page.

Key points about data submitted using HttpPost


1. POST - Submits data to be processed to a specified resource
2. A Submit button will always initiate an HttpPost request.
3. Data is submitted in http request body.
4. Data is not visible in the url.
5. It is more secured but slower as compared to GET.
6. It use heap method for passing form variable
7. It can post unlimited form variables.
8. It is advisable for sending critical data which should not visible to users.

Data Annotation Validator Attributes


1. DataType
Specify the datatype of a property
2. DisplayName
specify the display name for a property.
3. DisplayFormat
specify the display format for a property like different format for Date proerty.
4. Required
Specify a property as required.
5. ReqularExpression
validate the value of a property by specified regular expression pattern.
6. Range
validate the value of a property with in a specified range of values.
7. StringLength
specify min and max length for a string property.
8. MaxLength
specify max length for a string property.
9. Bind
specify fields to include or exclude when adding parameter or form values to model properties.
10. ScaffoldColumn
specify fields for hiding from editor forms.

You might also like