C# Interview Uestions
C# Interview Uestions
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.
// 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.
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’.
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.
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.
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.
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.
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.
There are three types of sharing using the static keyword. They are:
Static Method
Static Field
Static Class
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 :
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.
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:
class Point
{
public Point()
{
this.x = -1;
this.y = -1;
Console.WriteLine("Deafult Constructor Called");
objectCount++;
}
private int x, y;
public static int objectCount = 0;
}
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
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));
}
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.
Constants:
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).
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
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 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.
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.
class Program
{
static void Main(string[] args)
{
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:
Read Only:
1. Read only variables can be assigned values either at runtime or at the time of instance initialization
via constructor
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.
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: Sure sir, what kind of account do you want to open?
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.
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.
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.
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:
// Account Number field is a common field for all the account types
public string AccountNumber { get; set; }
// this variable will hold the summary of all the transaction that took place
protected string TransactionSummary { get; set; }
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:
Let's see our CurrentAccount class which also derives from the abstract base class.
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.
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();
}
Deposit:40000
Withdraw:1000
Withdraw:1000
Withdraw:1000
Sending Email for Account S12345
Deposit:190000
Withdraw:1000
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().
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:
class ClassSuper
{
public void MethdoTestPublic()
{
Console.WriteLine("ClassTest.MethdoTestPublic");
}
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
class ClassSuper
{
// Do your code
}
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
}
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
}
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.
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.
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.
**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.
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
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
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)
if (bDispose)
{
objSafeHandle.Dispose();
// Free any other managed objects here.
}
if (disposing)
{
// Free any other managed objects here.
//
}
~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.
//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
In the above sample after printing 1, using block gets end and calls Dispose method and then call
statement after using.
Re-view
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."
Example 2
Person behaves as a SON in house, at the same time that person behaves like an EMPLOYEE in the
office.
Example 3
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.
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
{
}
static void Main(string[] args)
{
TestOverloading obj = new TestOverloading();
obj.Add(5, 10);
Console.ReadLine();
}
}
}
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.
namespace PolymorphismByManishAgrahari
{
class Program
{
public class Base
{
public virtual void Show()
{
Console.WriteLine("Show From Base 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.
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.
namespace PolymorphismByManishAgrahari
{
class Program
{
public class Base
{
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.
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.
namespace PolymorphismByManishAgrahari
{
class Program
{
public class Base
{
Console.ReadLine();
}
}
}
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.
namespace PolymorphismByManishAgrahari
{
class Program
{
public class Base
{
Console.ReadLine();
}
}
}
The C# language specification states that "You cannot override a non-virtual method." See the
following example:
namespace PolymorphismByManishAgrahari
{
class Program
{
public class Base
{
Console.ReadLine();
}
}
}
Sealed Keyword
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.
namespace PolymorphismByManishAgrahari
{
class Program
{
public class Base
{
Console.ReadLine();
}
}
}
namespace PolymorphismByManishAgrahari
{
class Program
{
public class Base
{
Console.ReadLine();
}
}
}
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
Example:
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.)
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:
After this, we are accepting the two values from the user and passing those values to the delegate as
we do using method:
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?
Multicast delegates must contain only methods that return void, else there is a run-time exception.
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:
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
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
Output
Out Keyword
The out keyword passes arguments by reference. This is very similar to the ref keyword.
Example Code
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.
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
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
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.
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.
Array:
You need to specify the size of an array at the time of its declaration. It cannot be resized dynamically.
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.
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.
MyOldCurrencyExchange(500, 1.18);
MyNewCurrencyExchange (amount:500);
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 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:
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:
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;
}
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;
}
}
Abstract properties
Following is an example of implementing abstract properties in a class.
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.
//Incorrect
abstract sealed class absClass
{
}
//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.
//Incorrect
public abstract virtual int MultiplyTwoNumbers();
//Incorrect
publpublic abstract static int MultiplyTwoNumbers();
An example of interface:
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.
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.
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.
At this moment, you simply know that you want to be able to do things like these:
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.
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:
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.
Considering my example, a common question is: Why not start with the abstract class and avoid the
creation of an "useless" interface?
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.
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.
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?
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.
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.
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.
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.
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.
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.
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:
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.
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:
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.
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
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.
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.
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.
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:
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:
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.
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:
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.
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.
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.
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.
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.
And now lets have a good version in our code using this stored procedure.
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.
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.
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.
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.
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. }
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
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
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;
Output
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.
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.
Simple Example
Hide Copy Code
n => n % 2 == 1
You can read n => n % 2 == 1 like: "input parameter named n goes to anonymous function which
returns true if the input is odd".
I didn't mention expression trees/run time advantages of lambda expression due to limited scope.
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.
There is performance costs associated with Finalize method since it doesn't clean the memory
immediately and called by GC automatically.
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.
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.
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.
.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;
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.
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.
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;
}
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;
There are some significant characteristics of Generic types that make them special to the conventional
non-generics type as follows;
Type Safety
Performance
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;
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;
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.
foreach(int i in obj)
{
Console.WriteLine(i); // unboxing
}
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;
foreach(int i in obj)
{
Console.WriteLine(i); //No unboxing
}
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:
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);
Console.ReadLine();
}
}
}
After compiling this Generic method implementation program, the output is as in the following;
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.
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);
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;
return sb.ToString();
}
}
public class Program
{
static void Main(string[] args)
{
//define Dictionary collection
Dictionary<string, emp> dObj = new Dictionary<string, emp>(2);
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:
The Queue collection property, methods and other specification definitions are found under the
Sysyem.Collection namespace. The following table defines the key members;
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();
//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:
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);
//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:
Here new Customer() will create object on heap and its address we are putting in reference
variable of type Object.
ArrayList
Hide Copy Code
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.
List
Hide Copy Code
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.
Or even you can create collection of custom types. For example, collection of Student type can be
created as:
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
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.
There is performance costs associated with Finalize method since it doesn't clean the memory
immediately and called by GC automatically.
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.
Class:
Structure:
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.