0% found this document useful (0 votes)
316 views110 pages

Interview Questions All in One

All the details are collected form 4-5 web site. include:- -Main OOPs Concept with Example -.Net & Asp.net Cocept - MVC important Questions -Sql Server - WPF

Uploaded by

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

Interview Questions All in One

All the details are collected form 4-5 web site. include:- -Main OOPs Concept with Example -.Net & Asp.net Cocept - MVC important Questions -Sql Server - WPF

Uploaded by

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

1.What is OOPS?

OOPS is abbreviated as Object Oriented Programming system in which programs are considered as
a collection of objects. Each object is nothing but an instance of a class.
2.Write basic concepts of OOPS?
Following are the concepts of OOPS and are as follows:.

1.Abstraction.
2.Encapsulation.
3.Inheritance.
4.Polymorphism.
3.What is a class?
A class is simply a representation of a type of object. It is the blueprint/ plan/ template that describe
the details of an object.

4.What is an object?
Object is termed as an instance of a class, and it has its own state, behavior and identity.

5.What is Encapsulation?
Encapsulation is an attribute of an object, and it contains all data which is hidden. That hidden data
can be restricted to the members of that class.

Levels are Public,Protected, Private, Internal and Protected Internal.

6.What is Polymorphism?
Polymorphism is nothing butassigning behavior or value in a subclass to something that was
already declared in the main class. Simply, polymorphism takes more than one form.

7.What is Inheritance?
Inheritance is a concept where one class shares the structure and behavior defined in another class.
Ifinheritance applied on one class is called Single Inheritance, and if it depends on multiple classes,
then it is called multiple Inheritance.

8.What are manipulators?


Manipulators are the functions which can be used in conjunction with the insertion (<<) and
extraction (>>) operators on an object. Examples are endl and setw.

9.Define a constructor?
Constructor is a method used to initialize the state of an object, and it gets invoked at the time of
object creation. Rules forconstructor are:.
•Constructor Name should be same asclass name.
•Constructor must have no return type.
10.Define Destructor?
Destructor is a method which is automatically called when the object ismade ofscope or destroyed.
Destructor name is also same asclass name but with the tilde symbol before the name.

11.What is Inline function?


Inline function is a technique used by the compilers and instructs to insert complete body of the
function wherever that function is used in the program source code.

12.What is avirtual function?


Virtual function is a member function ofclass and its functionality can be overridden in its derived
class. This function can be implemented by using a keyword called virtual, and it can be given
during function declaration.
Virtual function can be achieved in C++, and it can be achieved in C Languageby using function
pointers or pointers to function.

13.What isfriend function?


Friend function is a friend of a class that is allowed to access to Public, private or protected data in
that same class. If the function is defined outside the class cannot access such information.
Friend can be declared anywhere in the class declaration, and it cannot be affected by access control
keywords like private, public or protected.

14.What is function overloading?


Function overloading is defined as a normal function, but it has the ability to perform different
tasks. It allowscreation of several methods with the same name which differ from each other by
type of input and output of the function.
Example
void add(int& a, int& b);
void add(double& a, double& b);
void add(struct bob& a, struct bob& b);

15.What is operator overloading?


Operator overloading is a function where different operators are applied and depends on the
arguments. Operator,-,* can be used to pass through the function , and it has their own precedence
to execute.
Example:
class complex {
double real, imag;
public:
complex(double r, double i) :
real(r), imag(i) {}
complex operator+(complex a, complex b);
complex operator*(complex a, complex b);
complex& operator=(complex a, complex b);
}
a=1.2, b=6

16.What is an abstract class?


An abstract class is a class which cannot be instantiated. Creation of an object is not possible
withabstract class , but it can be inherited. An abstract class can contain only Abstract method.

17.What is a ternary operator?


Ternary operator is said to be an operator which takes three arguments. Arguments and results are of
different data types , and it is depends on the function. Ternary operator is also called asconditional
operator.

18.What is the use of finalize method


Finalize method helps to perform cleanup operations on the resources which are not currently used.
Finalize method is protected , and it is accessible only through this class or by a derived class.

19.What are different types of arguments?


A parameter is a variable used during the declaration of the function or subroutine and arguments
are passed to the function , and it should match with the parameter defined. There are two types of
Arguments.
•Call by Value – Value passed will get modified only inside the function , and it returns the
same value whatever it is passed it into the function.
•Call by Reference – Value passed will get modified in both inside and outside the functions
and it returns the same or different value.

20.What is super keyword?


Super keyword is used to invoke overridden method which overrides one of its superclass methods.
This keyword allows to access overridden methods and also to access hidden members of the
superclass.
It also forwards a call from a constructor to a constructor in the superclass.

21.What is method overriding?


Method overriding is a feature that allows sub class to provide implementation of a method that is
already defined in the main class. This will overrides the implementation in the superclass by
providing the same method name, same parameter and same return type.

22.What is an interface?
An interface is a collection of abstract method. If the class implements an inheritance, and then
thereby inherits all the abstract methods of an interface.

23.What is exception handling?


Exception is an event that occurs during the execution of a program. Exceptions can be of any type
– Run time exception, Error exceptions. Those exceptions are handled properly through exception
handling mechanism like try, catch and throw keywords.

24.What are tokens?


Token is recognized by a compiler and it cannot be broken down into component elements.
Keywords, identifiers, constants, string literals and operators are examples of tokens.
Even punctuation characters are also considered as tokens – Brackets, Commas, Braces and
Parentheses.

25.Difference between overloading and overriding?


Overloading is static binding whereas Overriding is dynamic binding. Overloading is nothing but
the same method with different arguments , and it may or may not return the same value in the same
class itself.
Overriding is the same method names with same arguments and return types associates with the
class and its child class.

26.Difference between class and an object?


An object is an instance of a class. Objects hold any information , but classes don’t have any
information. Definition of properties and functions can be done at class and can be used by the
object.
Class can have sub-classes, and an object doesn’t have sub-objects.

27.What is an abstraction?
Abstraction is a good feature of OOPS , and it shows only the necessary details to the client of an
object. Means, it shows only necessary details for an object, not the inner details of an object.
Example – When you want to switch On television, it not necessary to show all the functions of TV.
Whatever is required to switch on TV will be showed by using abstract class.
28.What are access modifiers?
Access modifiers determine the scope of the method or variables that can be accessed from other
various objects or classes. There are 5 types of access modifiers , and they are as follows:.
• Private.
•Protected.
•Public.
•Friend.
•Protected Friend.
29.What is sealed modifiers?
Sealed modifiers are the access modifiers where it cannot be inherited by the methods. Sealed
modifiers can also be applied to properties, events and methods. This modifier cannot be applied to
static members.

30.How can we call the base method without creating an instance?


Yes, it is possible to call the base method without creating an instance. And that method should be,.
Static method.
Doing inheritance from that class.-Use Base Keyword from derived class.

31.What is the difference between new and override?


The new modifier instructs the compiler to use the new implementation instead of the base class
function. Whereas, Override modifier helps to override the base class function.

32.What are the various types of constructors?


There are three various types of constructors , and they are as follows:.
- Default Constructor – With no parameters.
- Parametric Constructor – With Parameters. Create a new instance of a class and also passing
arguments simultaneously.
-Copy Constructor – Which creates a new object as a copy of an existing object.

33.What is early and late binding?


Early binding refers to assignment of values to variables during design time whereas late binding
refers to assignment of values to variables during run time.

34.What is ‘this’ pointer?


THIS pointer refers to the current object of a class. THIS keyword is used as a pointer which
differentiates between the current object with the global object. Basically, it refers to the current
object.

35.What is the difference betweenstructure and a class?


Structure default access type is public , but class access type is private. A structure is used for
grouping data whereas class can be used for grouping data and methods. Structures are exclusively
used for dataand it doesn’t require strict validation , but classes are used to encapsulates and inherit
data which requires strict validation.

36.What is the default access modifier in a class?


The default access modifier of a class is Private by default.

37.What is pure virtual function?


A pure virtual function is a function which can be overridden in the derived classbut cannot be
defined. A virtual function can be declared as Pure by using the operator =0.
Example -.
Virtual void function1() // Virtual, Not pure
Virtual void function2() = 0 //Pure virtual

38.What are all the operators that cannot be overloaded?


Following are the operators that cannot be overloaded -.
1.Scope Resolution (:: )
2.Member Selection (.)
3.Member selection through a pointer to function (.*)
39.What is dynamic or run time polymorphism?
Dynamic or Run time polymorphism is also known as method overriding in which call to an
overridden function is resolved during run time, not at the compile time. It means having two or
more methods with the same name,same signature but with different implementation.

40.Do we require parameter for constructors?


No, we do not require parameter for constructors.

41.What is a copy constructor?


This is a special constructor for creating a new object as a copy of an existing object. There will be
always only on copy constructor that can be either defined by the user or the system.

42.What does the keyword virtual represented in the method definition?


It means, we can override the method.

43.Whether static method can use non static members?


False.

44.What arebase class, sub class and super class?


Base class is the most generalized class , and it is said to be a root class.Sub class is a class that
inherits from one or more base classes.Super class is the parent class from which another class
inherits.

45.What is static and dynamic binding?


Binding is nothing but the association of a name with the class. Static binding is a binding in which
name can be associated with the class during compilation time , and it is also called as early
Binding.Dynamic binding is a binding in which name can be associated with the class during
execution time , and it is also called as Late Binding.

46.How many instances can be created for an abstract class?


Zero instances will be created for an abstract class.

47.Which keyword can be used for overloading?


Operator keyword is used for overloading.

48.What is the default access specifier in a class definition?


Private access specifier is used in a class definition.

49.Which OOPS concept is used as reuse mechanism?


Inheritance is the OOPS concept that can be used as reuse mechanism.

50.Which OOPS concept exposes only necessary information to the calling functions?
Data Hiding / Abstraction
Abstraction
Abstraction refers to the act of representing essential features without including the background
details or explanations.
•Abstraction defines way to abstract or hide your data and members from outside world.
•Classes use the concept of abstraction and are defined as a list of abstract attributes.
•Simply speaking Abstraction is hiding the complexities of your class or struct or in a generic
term Type from outer world.
•This is achieved by means of access specifiers.
Access Modifier Description (who can access)
Private Only members within the same type. (default for type members)
Protected Only derived types or members of the same type.
Only code within the same assembly. Can also be code external to
Internal
object as long as it is in the same assembly. (default for types)
Either code from derived type or code in the same assembly.
Protected internal
Combination of protected OR internal.
Any code. No inheritance, external type, or external assembly
Public
restrictions.
Code Example :
namespace AbstractionExample
{
public abstract class Shape {
private float _area;
private float _perimeter;
public float Area { get { return _area; } set { _area = value; } }
public float Perimeter { get { return _perimeter; } set { _perimeter = value; } }
public abstract void CalculateArea(); public abstract void CalculatePerimeter(); }
}
Advantages of abstraction are
the hiding of implementation details, component reuse, extensibility, and testability. When we hide
implementation details, we reveal a cleaner, more comprehensible and usable interface to our users.
We are separating our interface from our implementation, and this makes component reuse more
practical. Many, if not all of the object-oriented concepts we have discussed throughout this
document play a role in the abstraction principle. Working together, their end goal is the same, to
produce software that is flexible, testable, maintainable, and extensible.

Definition

Abstraction is one of the principle of object oriented programming. It is used to display only
necessary and essential features of an object to ouside the world.Means displaying what is
necessary and encapsulate the unnecessary things to outside the world.Hiding can be achieved by
using "private" access modifiers.

Note - Outside the world means when we use reference of object then it will show only necessary
methods and properties and hide methods which are not necessary.

Implementation of Abstraction
To implement abstraction let's take an example of a car. We knows a car, Car is made of name of
car, color of car, steering, gear, rear view mirror, brakes, silencer, exhaust system, diesal engine, car
battery, car engine and other internal machine details etc.

Now lets think in terms of Car rider or a person who is riding a car. So to drive a car what a car
rider should know from above category before he starts a car driving.

Necessary things means compulsary to know before starting a car

1. Name of Car
2. Color of Car
3. Steering
4. Rear View Mirror
5. Brakes
6. Gear

Unnecessary things means not that compulsary to know for a Car rider

1. Internal Details of a Car


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

public class Car

private string _nameofcar = "My Car";


private string _colorofcar = "Red";

public string NameofCar

set

_nameofcar = value;
}
get

return _nameofcar;
}
}

public string ColorofCar

set

_colorofcar = value;
}
get

return _colorofcar;
}
}

public void Steering()

Console.WriteLine("Streering of Car");
}
public void RearViewMirror()

Console.WriteLine("RearViewMirror of Car");
}

public void Brakes()

Console.WriteLine("Brakes of Car");
}
public void Gear()

Console.WriteLine("Gear of Car");
}

private void InternalDetailsofCar()

Console.WriteLine("InternalDetailsofCar of Car");
}

private void CarEngine()

Console.WriteLine("CarEngine of Car");
}

private void DiesalEngine()

Console.WriteLine("DiesalEngine of Car");
}

private void ExhaustSystem()

Console.WriteLine("ExhaustSystem of Car");
}

private void Silencer()

Console.WriteLine("Silencer of Car");
}

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

How we can achieve Encapsulation


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

class Employee{
private void AccountInformation(){
Console.WriteLine("Displaying Account Details");
}

Why to use Encapsulation


Encapsulation means protecting important data inside the class which we do not want to be exposed
outside of the class.Lets consider example of a Television(TV).
If you have seen important TV machine, TV connections and TV color tube is hidden inside the TV
case which is not been exposed for viewers like us and exposed only neccessary things of a TV like
TV Channel keys, TV volume keys, ON/OFF switch, Cable Switch and TV remote control for
viewers to use it.This means TV machine, TV connections and TV color tube is an unwanted data
and not needed for viewers to see is been hidden from outside the world.So encapsulation means
hiding the important features of a class which is not been needed to be exposed outside of a class
and exposing only necessary things of a class.Here hidden part of a class acts like Encapsulation
and exposed part of a class acts like Abstraction.

class clsTelevision{

private void TVmachine(){


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

private void TVcolortube(){


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

public void TVKeys(){


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

public void TVRemote(){


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

public void TVScreen(){


Console.WriteLine("Wide Screen of a Television");
}}
The following are the benefits of encapsulation:
•Protection of data from accidental corruption
•Specification of the accessibility of each of the members of a class to the code outside the class
•Flexibility and extensibility of the code and reduction in complexity
•Lower coupling between objects and hence improvement in code maintainability.
Techopedia explains Encapsulation
Encapsulation in C# is implemented with different levels of access to object data that can be
specified using the following access modifiers:
• Public: Access to all code in the program
• Private: Access to only members of the same class
• Protected: Access to members of same class and its derived classes
• Internal: Access to current assembly
• Protected Internal: Access to current assembly and types derived from containing class

Abstraction Encapsulation
Abstraction solves the problem in the design
Encapsulation solves the problem in the implementation level.
level.
Abstraction is used for hiding the unwanted Encapsulation is hiding the code and data into a single unit to protect the
data and giving only relevant data. data from outer world.
Abstraction is set focus on the object instead of Encapsulation means hiding the internal details or mechanics of how an
how it does it. object does something.
Abstraction is outer layout in terms of design. Encapsulation is inner layout in terms of implementation.
For Example: - Outer Look of a iPhone, like it For Example: - Inner Implementation detail of a iPhone, how Display
has a display screen. Screen are connect with each other using circuits

Difference between Encapsulation and Abstraction in OOPS

Abstraction and Encapsulation are two important Object Oriented Programming (OOPS) concepts.
Encapsulation and Abstraction both are interrelated terms.

Real Life Difference Between Encapsulation and Abstraction

Encapsulate means to hide. Encapsulation is also called data hiding.You can think Encapsulation like a
capsule (medicine tablet) which hides medicine inside it. Encapsulation is wrapping, just hiding properties
and methods. Encapsulation is used for hide the code and data in a single unit to protect the data from the
outside the world. Class is the best example of encapsulation.

Abstraction refers to showing only the necessary details to the intended user. As the name suggests,
abstraction is the "abstract form of anything". We use abstraction in programming languages to make
abstract class. Abstract class represents abstract view of methods and properties of class.

Implementation Difference Between Encapsulation and Abstraction

1. Abstraction is implemented using interface and abstract class while Encapsulation is implemented using
private and protected access modifier.

2. OOPS makes use of encapsulation to enforce the integrity of a type (i.e. to make sure data is used in an
appropriate manner) by preventing programmers from accessing data in a non-intended manner. Through
encapsulation, only a predetermined group of functions can access the data. The collective term for
datatypes and operations (methods) bundled together with access restrictions (public/private, etc.) is a class.

3. Example of Encapsulation

Class Encapsulation
{
private int marks;

public int Marks


{
get { return marks; }
set { marks = value;}
}
}

4. Example of Abstraction

abstract class Abstraction


{
public abstract void doAbstraction();
}

public class AbstractionImpl: Abstraction


{
public void doAbstraction()
{
//Implement it
}
}
Abstract Class
An abstract class cannot be instantiated. The purpose of an abstract class is to provide a common
definition of a base class that multiple derived classes can share. For example, a class library may
define an abstract class that is used as a parameter to many of its functions, and require
programmers using that library to provide their own implementation of the class by creating a
derived class.
Abstract classes may also define abstract methods. This is accomplished by adding the
keyword abstract before the return type of the method.

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.

abstract class absClass


{
public abstract void abstractMethod();
}

Also, note that an abstract class does not mean that it should contain abstract members. Even we can have an
abstract class only with non abstract members. For example:
abstract class absClass
{
public void NonAbstractMethod()
{
Console.WriteLine("NonAbstract Method");
}
}

A sample program that explains abstract classes:


using System;

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

//An abstract method, to be


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

//A Child Class of absClass


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

absDerived calculate = new absDerived();


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

//using override keyword,


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

In the above sample, you can see that the abstract class absClass contains two
methods AddTwoNumbers andMultiplyTwoNumbers. AddTwoNumbers is a non-abstract method
which contains implementation andMultiplyTwoNumbers 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 andMultiplyTwoNumbers. 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.

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

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

//Derived class from absClass2


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

In the above example, absClass1 contains two abstract methods AddTwoNumbers and MultiplyTwoNumbers.
TheAddTwoNumbers is implemented in the derived class absClass2. The class absDerived is derived
from absClass2and the MultiplyTwoNumbers is implemented there.

Abstract properties
Following is an example of implementing abstract properties in a class.
//Abstract Class with abstract properties
abstract class absClass
{
protected int myNumber;
public abstract int numbers
{
get;
set;
}
}

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

In the above example, there is a protected member declared in the abstract


class.The get/set properties for the member variable myNumber is defined in the derived
class absDerived.

Important rules applied to abstract classes


An abstract class cannot be a sealed class. I.e. the following declaration is incorrect.
//Incorrect
abstract sealed class absClass
{
}

Declaration of abstract methods are only allowed in abstract classes.


An abstract method cannot be private.
//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();

An abstract member cannot be static.


//Incorrect
publpublic abstract static int MultiplyTwoNumbers();

Abstract class vs. Interface


An abstract class can have abstract members as well non abstract members. But in an interface all the
members are implicitly abstract and all the members of the interface must override to its derived class.
An example of interface:
interface iSampleInterface
{
//All methods are automaticall abstract
int AddNumbers(int Num1, int Num2);
int MultiplyNumbers(int Num1, int Num2);
}

Defining an abstract class with abstract members has the same effect to defining an interface.
The members of the interface are public with no implementation. Abstract classes can have protected
parts, static methods, etc.
A class can inherit one or more interfaces, but only one abstract class.
Abstract classes can add more functionality without destroying the child classes that were using the old
version. In an interface, creation of additional functions will have an effect on its child classes, due to the
necessary implementation of interface methods to classes.
The selection of interface or abstract class depends on the need and design of your project. You can
make an abstract class, interface or combination of both depending on your needs.

Abstract Method
In an abstract class a method which has a keyword "abstract" and doesn't provide any
implementation is called abstract method.The implementation logic of abstract methods is provided
by the child classes or derived classes.Child classes use keyword "override" with same method
name (as abstract method name) to provide further implementation of abstract methods.
Non Abstract Method
In an abstract class a method which doesn't have a keyword "abstract" and provide any
implementation is called non abstract method.
Why Abstract Class
Abstract class enforces derived classes to provide all implementation logic for abstract methods or
properties.
Use of an Abstract Class
Use abstract class when you want to create a common base class for a family of types and with
some implementation Subclass only a base class in a hierarchy to which the class logically belongs.

The purpose of abstract class is to provide default functionality to its sub classes.

When a method is declared as abstract in the base class then every derived class of that class
must provide its own definition for that method.

An abstract class can also contain methods with complete implementation, besides abstract
methods.

When a class contains at least one abstract method, then the class must be declared as abstract
class.

It is mandatory to override abstract method in the derived class.

When a class is declared as abstract class, then it is not possible to create an instance for that
class. But it can be used as a parameter in a method.

Abstract method: When a class contains an abstract method, that class must be declared as
abstract. The abstract method has no implementation and thus, classes that derive from that abstract
class, must provide an implementation for this abstract method.

Virtual method: A class can have a virtual method. The virtual method has an implementation.
When you inherit from a class that has a virtual method, you can override the virtual method and
provide additional logic, or replace the logic with your own implementation.

When to use what: In some cases, you know that certain types should have a specific method, but,
you don't know what implementation this method should have.
In such cases, you can create an interface which contains a method with this signature. However, if
you have such a case, but you know that implementors of that interface will also have another
common method (for which you can already provide the implementation), you can create an
abstract class. This abstract class then contains the abstract method (which must be overriden), and
another method which contains the 'common' logic.
A virtual method should be used if you have a class which can be used directly, but for which you
want inheritors to be able to change certain behaviour, although it is not mandatory.

Use of Non Abstract Method of Abstract Class in C#


You can have non abstract method in abstract class; as such I didn’t find any use of these methods. Yes this is an
option. May be it is useful in some situations when you want to call those methods inside your abstract methods.
As per abstraction rules, you cannot create the object of abstract class, means you cannot use
the"new" keyword.
You can create any class as an abstract class with the help of “Abstract” keyword; even you can create
any method as an abstract method inside the class. Abstract class can have both type of method
“Abstract” & “Non Abstract”. You can inherit these classes inside the non abstract classes.
Abstract classes cannot have the implementations details of abstract methods.
Abstract Classes
An Abstract class is used when there is a common functionality to be shared between the subclasses,
but the superclass itself will never exist. For example, a class Person will never exist. However a
class Woman will. Instead of repeating all the methods that are in Woman, in Man, Boy and Girl, we
simply raise it to the superclass, so they all have access to this functionality, and can override the
methods that they want to perform differently.
Interfaces
Interfaces are used when there is a requirement. The way I look at them is like a contract. The
agreement being that any class that implements the Interface, will have to provide code for a certain
number of methods.
For example, A class Rock and a class Ball can both be thrown. Instead of the method to throw a ball
having to take into account every object that can be thrown, if every object Implements
the ThrowingItem Interface (I didn't want to use the word Throwable for obvious reasons), then the
method can just accept an object of type ThrowingItem and knows for a fact that the agreed methods
will be there.
This enables loose coupling between the throw method and the classes that use it, because all
communication is done through the interface.

If you have a type that can be designed as either an interface or an abstract class, why would you choose abstract
class?
In that sense, we only use abstract class when some features cannot be done in interface:
1.state. though an interface could ask subclasses to implement state, it might be more convenient to use an
abstract super class to hold the state.
2.restricting member access to protected. while all things in interface are public
3.static methods. (note that in Java 8, probably, interface can have static methods)
4.concrete methods with implementations. (note that in Java 8, interface methods can have defualt impl)
5.add more concrete methods without breaking subclasses. (note that in Java 8, we can add more methods to
an existing interface if the methods have default impls)

Virtual Methods in C#.NET with example


When you want to allow a derived class to override a method of the base class, within the base class
method must be created as virtual method and within the derived class method must be created
using the keyword override.

When a method declared as virtual in base class, then that method can be defined in base class and
it is optional for the derived class to override that method.

When it needs same definition as base class, then no need to override the method and if it needs
different definition than provided by base class then it must override the method.

Method overriding also provides more than one form for a method. Hence it is also an example for
polymorphism.

The following example creates three classes shape, circle and rectangle where circle and
rectangle are inherited from the class shape and overrides the methods Area() and
Circumference() that are declared as virtual in Shape class.

using System;
namespace ProgramCall
{
class Shape
{
protected float R, L, B;
public virtual float Area()
{
return 3.14F * R * R;
}
public virtual float Circumference()
{
return 2 * 3.14F * R;
}
}
class Rectangle : Shape
{
public void GetLB()
{
Console.Write("Enter Length : ");
L = float.Parse(Console.ReadLine());
Console.Write("Enter Breadth : ");
B = float.Parse(Console.ReadLine());
}
public override float Area()
{
return L * B;
}
public override float Circumference()
{
return 2 * (L + B);
}
}
class Circle : Shape
{
public void GetRadius()
{
Console.Write("Enter Radius : ");

R = float.Parse(Console.ReadLine());
}
}

class MainClass
{
static void Main()
{
Rectangle R = new Rectangle();
R.GetLB();
Console.WriteLine("Area : {0}", R.Area());
Console.WriteLine("Circumference : {0}", R.Circumference());
Console.WriteLine();
Circle C = new Circle();
C.GetRadius();
Console.WriteLine("Area : {0}", C.Area());
Console.WriteLine("Circumference : {0}", C.Circumference());
Console.Read();
}
}
}

A virtual method is a method that can be redefined in derived classes. A virtual


method has an implementation in a base class as well as derived the class. It is used
when a method's basic functionality is the same but sometimes more functionality is
needed in the derived class. A virtual method is created in the base class that can be
overriden in the derived class. We create a virtual method in the base class using the
virtual keyword and that method is overriden in the derived class using the override
keyword.

When a method is declared as a virtual method in a base class then that method can be
defined in a base class and it is optional for the derived class to override that method. The
overriding method also provides more than one form for a method. Hence it is also an example for
polymorphism.
When a method is declared as a virtual method in a base class and that method has the same
definition in a derived class then there is no need to override it in the derived class. But when a
virtual method has a different definition in the base class and the derived class then there is a need
to override it in the 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.
Virtual Method
1.By default, methods are non-virtual. We can't override a non-virtual method.
2.We can't use the virtual modifier with the static, abstract, private or override modifiers.

Method Overriding in C#.NET


Creating a method in derived class with same signature as a method in base class is called as
method overriding.
Same signature means methods must have same name, same number of
arguments and same type of arguments.
Method overriding is possible only in derived classes, but not within the same
class.

When derived class needs a method with same signature as in base class, but
wants to execute different code than provided by base class then method
overriding will be used.

To allow the derived class to override a method of the base class, C# provides two
options,virtual methods and abstract methods.

Examples for Method Overriding in C#


using System;

namespace methodoverriding
{
class BaseClass
{
public virtual string YourCity()
{
return "New York";
}
}
class DerivedClass : BaseClass
{
public override string YourCity()
{
return "London";
}
}
class Program
{
static void Main(string[] args)
{
DerivedClass obj = new DerivedClass();
string city = obj.YourCity();
Console.WriteLine(city);
Console.Read();
}
}
}
Output

London
Example - 2 implementing abstract method
using System;

namespace methodoverridingexample
{
abstract class BaseClass
{
public abstract string YourCity();

}
class DerivedClass : BaseClass
{
public override string YourCity() //It is mandatory to implement absract method
{
return "London";
}

private int sum(int a, int b)


{
return a + b;
}
}
class Program
{

static void Main(string[] args)


{
DerivedClass obj = new DerivedClass();
string city = obj.YourCity();
Console.WriteLine(city);
Console.Read();
}
}
}

Output
London
Interface
An interface looks like a class but has got no implementation. In an interface we cannot do any
implementation but we can declare signatures of properties, methods, delegates and events.
Implementation part is been handle by the class that implements the interface. Implemented
interface enforces the class like a standard contract to provide all implementation of interface
members.
We can implement single interface or multiple interfaces to the class. By default interfaces are
public.
We declare interface by using "interface" keyword.

interface IEmployee{

void DisplayEmployeeDetails();

Above syntax shows simple demonstration of interface "IEmployee" with signature of a method
"DisplayEmployeeDetails". Now let's implement the same interface to a class.
class clsEmployee : IEmployee
{
public void DisplayEmployeeDetails(){
Console.WriteLine(“Displaying employee details…”);
}
}

Benefits of using an interface


Implemented interface enforces the class like a standard contract to provide all implementation of
interface members.
In architecting the project we can define the proper naming conventions of methods, properties in
an interface so that while implementing in a class we use the name conventions.

We can use the "interface" as a pointer in the different layers of applications.We can use an interface
for implementing run time polymorphism.

Various Forms of implementing interface


There are two of ways of implementing interfaces

Explicit
Implicit

Explicit interface implementation

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

public class Employee : IEmployee


{
void IEmployee.DisplayEmployeeDetails()
{
Console.WriteLine("IEmployee Employee Name -->.....");
}
}
In which scenario we use explicit interface implementation
When we have two different interfaces with same method name then in that scenario we can use
explicit interface implementation.
Example of Explicit Interface

public interface IEmployee{


void DisplayEmployeeDetails();
}

public interface ICompany{


void DisplayEmployeeDetails();
}

In order to implement an interface explicitly we have to define the interface name followed by (".")
dot operator before method name as shown in below snipped code.
public class Employee : IEmployee,ICompany
{
void ICompany.DisplayEmployeeDetails(){
Console.WriteLine("ICompany Employee Name --> Questpond and Employee Code --> 009");
}
void IEmployee.DisplayEmployeeDetails(){
Console.WriteLine("IEmployee Employee Name --> Questpond and Employee Code --> 009");
}
}

Properties Of Interface:-
• Supports multiple inheritance(Single Class can implement multiple interfaces).
• Contains only incomplete method.
• Can not Contains data members.
• By Default interface members is public (We Can not set any access modifier into interface
members).
• Interface can not contain constructors.
• hide implementation details of classes from each other
• facilitate reuse of software

Interface characteristics in the “code world”


• An iterface defines only the properties and method signatures and not the actual
implementation. I mean that in a class declaration we implement fields,properties,methods
and events. In an interface we just define what properties/methods the class should have.
• Requires that classes which implement an interface must ”honour” the property and method
signatures. Basically are like contracts for classes. Classes which implement an interface
must implement the methods and the properties of the interface.
• Many classes can implement a particular interface method, in their own way.
• An interface may inherit from multiple base interfaces.
• A class may implement-inherit from multiple interfaces.
• A C# class may only inherit from one class.
Feature Interface Abstract class

Multiple inheritance A class may inherit several A class may inherit only
interfaces. one abstract class.

Default implementation An interface cannot An abstract class can


provide any code, just the provide complete, default
signature. code and/or just the details
that have to be overridden.

Access Modfiers An interface cannot have An abstract class can


access modifiers for the contain access modifiers
subs, functions, properties for the subs, functions,
etc everything is assumed properties
as public

Core VS Peripheral Interfaces are used to An abstract class defines


define the peripheral the core identity of a class
abilities of a class. In other and there it is used for
words both Human and objects of the same type.
Vehicle can inherit from a
IMovable interface.

Homogeneity If various implementations If various implementations


only share method are of the same kind and
signatures then it is better use common behaviour or
to use Interfaces. status then abstract class is
better to use.

Speed Requires more time to find Fast


the actual method in the
corresponding classes.

Adding functionality If we add a new method to If we add a new method to


(Versioning) an Interface then we have an abstract class then we
to track down all the have the option of
implementations of the providing default
interface and define implementation and
implementation for the therefore all the existing
new method. code might work properly.

Fields and Constants No fields can be defined in An abstract class can have
interfaces fields and constrants
defined
Polymorphism in C#.NET
According to MSDN, Through inheritance, a class can be used as more than one type; it can be
used as its own type, any base types, or any interface type if it implements interfaces. This is
called polymorphism.

In C#, every type is polymorphic. Types can be used as their own type or as a Object instance,
because any type automatically treats Object as a base type.

Polymorphism means having more than one form. Overloading and overriding are used to
implement polymorphism. Polymorphism is classified into compile time polymorphism or
early binding or static binding and Runtime polymorphism or late binding or dynamic binding

Polymorphism Examples
• Method Overloading
• Method Overriding
Compile time Polymorphism or Early Binding

The polymorphism in which compiler identifies which polymorphic form it has to


execute at compile time it self is called as compile time polymorphism or early
binding.

Advantage of early binding is execution will be fast. Because every thing about the
method is known to compiler during compilation it self and disadvantage is lack of
flexibility.

Examples of early binding are overloaded methods, overloaded operators and


overridden methods that are called directly by using derived objects.

Runtime Polymorphism or Late Binding

The polymorphism in which compiler identifies which polymorphic form to execute at


runtime but not at compile time is called as runtime polymorphism or late binding.

Advantage of late binding is flexibility and disadvantage is execution will be slow as


compiler has to get the information about the method to execute at runtime.

Example of late binding is overridden methods that are called using base class object.
Static Class
A static class is basically the same as a non-static class, but there is one difference: a static class
cannot be instantiated. In other words, you cannot use the new keyword to create a variable of the
class type. Because there is no instance variable, you access the members of a static class by using
the class name itself. For example, if you have a static class that is named UtilityClass that has a
public method named MethodA, you call the method as shown in the following example:
UtilityClass.MethodA();

A static class can be used as a convenient container for sets of methods that just operate on input
parameters and do not have to get or set any internal instance fields. For example, in the .NET
Framework Class Library, the static System.Math class contains methods that perform mathematical
operations, without any requirement to store or retrieve data that is unique to a particular instance of
the Math class. That is, you apply the members of the class by specifying the class name and the
method name, as shown in the following example.

double dub = -3.14;


Console.WriteLine(Math.Abs(dub));
Console.WriteLine(Math.Floor(dub));
Console.WriteLine(Math.Round(Math.Abs(dub)));

// Output:
// 3.14
// -4
// 3
As is the case with all class types, the type information for a static class is loaded by the .NET
Framework common language runtime (CLR) when the program that references the class is
loaded. The program cannot specify exactly when the class is loaded. However, it is guaranteed to
be loaded and to have its fields initialized and its static constructor called before the class is
referenced for the first time in your program. A static constructor is only called one time, and a
static class remains in memory for the lifetime of the application domain in which your program
resides.

The following list provides the main features of a static class:


•Contains only static members.
•Cannot be instantiated.
•Is sealed.
•Cannot contain Instance Constructors.

Creating a static class is therefore basically the same as creating a class that contains only static
members and a private constructor. A private constructor prevents the class from being instantiated.
The advantage of using a static class is that the compiler can check to make sure that no instance
members are accidentally added. The compiler will guarantee that instances of this class cannot be
created.
Static classes are sealed and therefore cannot be inherited. They cannot inherit from any class
except Object. Static classes cannot contain an instance constructor; however, they can contain a
static constructor. Non-static classes should also define a static constructor if the class contains
static members that require non-trivial initialization. For more information, see Static Constructors
(C# Programming Guide).
public
static class TemperatureConverter
{
public static double CelsiusToFahrenheit(string temperatureCelsius)
{
// Convert argument to double for calculations.
double celsius = Double.Parse(temperatureCelsius);

// Convert Celsius to Fahrenheit.


double fahrenheit = (celsius * 9 / 5) + 32;

return fahrenheit;
}
public static double FahrenheitToCelsius(string temperatureFahrenheit)
{
// Convert argument to double for calculations.
double fahrenheit = Double.Parse(temperatureFahrenheit);

// Convert Fahrenheit to Celsius.


double celsius = (fahrenheit - 32) * 5 / 9;

return celsius;
}
}
class TestTemperatureConverter
{
static void Main()
{
Console.WriteLine("Please select the convertor direction");
Console.WriteLine("1. From Celsius to Fahrenheit.");
Console.WriteLine("2. From Fahrenheit to Celsius.");
Console.Write(":");
string selection = Console.ReadLine();
double F, C = 0;
switch (selection)
{
case "1":
Console.Write("Please enter the Celsius temperature: ");
F = TemperatureConverter.CelsiusToFahrenheit(Console.ReadLine());
Console.WriteLine("Temperature in Fahrenheit: {0:F2}", F);
break;

case "2":
Console.Write("Please enter the Fahrenheit temperature: ");
C = TemperatureConverter.FahrenheitToCelsius(Console.ReadLine());
Console.WriteLine("Temperature in Celsius: {0:F2}", C);
break;

default:
Console.WriteLine("Please select a convertor.");
break;
}

// Keep the console window open in debug mode.


Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
Static you can use the method of the class which is static, but you make sure that the value
gets changed as you required.

If you are using the class and object concept it means that you are using the OOPS concepts.

Static class is used when you are aware of that the value that you are going to use in entire
application will remain same means that at one place you will set the value and from other
place you will get that value, at that point of time it's better to use static class.

The following are rules to create a static class:

Rule#1. a static class must contain the static keyword in the class declaration.
Rule#2. a method should be static i.e. the method declaration must contain the static keyword.
Rule#3. the Constructor must be static because a static class doesn't allow an instance constructor.
Rule#4. the Constructor must not contain an access modifier.
Rule#5. a Static class can't implement an inteface.
Rule#6. a Static class can't be a base class i.e. it cannot be derived from.

• Is a class whose members must be accessed without an instance of the class. In other words,
the members of a static class must be accessed directly from (using the name of) the class,
using the period operator

• Is a class whose members must be created as static. In other words,


you cannot add a non-static member to a static class: all members,
except for constants, must be static
Static Member
A non-static class can contain static methods, fields, properties, or events. The static member is
callable on a class even when no instance of the class has been created. The static member is always
accessed by the class name, not the instance name. Only one copy of a static member exists,
regardless of how many instances of the class are created. Static methods and properties cannot
access non-static fields and events in their containing type, and they cannot access an instance
variable of any object unless it is explicitly passed in a method parameter.
It is more typical to declare a non-static class with some static members, than to declare an entire
class as static. Two common uses of static fields are to keep a count of the number of objects that
have been instantiated, or to store a value that must be shared among all instances.
Static methods can be overloaded but not overridden, because they belong to the class, and not to
any instance of the class.
Although a field cannot be declared as static const, a const field is essentially static in its behavior.
It belongs to the type, not to instances of the type. Therefore, const fields can be accessed by using
the same ClassName.MemberName notation that is used for static fields. No object instance is
required.
C# does not support static local variables (variables that are declared in method scope).
You declare static class members by using the static keyword before the return type of the member,
as shown in the following example:
public class Automobile
{
public static int NumberOfWheels = 4;
public static int SizeOfGasTank
{
get
{
return 15;
}
}
public static void Drive() { }
public static event EventType RunOutOfGas;

// Other non-static fields and properties...


}

Static Method:-
Static methods have no instances. They are called with the type name, not an instance identifier.
They are slightly faster than instance methods because of this. Static methods can be public or
private.

A static function, unlike a regular (instance) function, is not associated with an instance of the class.
A static class is a class which can only contain static members, and therefore cannot be
instantiated.
For example:
class SomeClass {
public int InstanceMethod() { return 1; }
public static int StaticMethod() { return 42; }
}
In order to call InstanceMethod, you need an instance of the class:
SomeClass instance = new SomeClass();
instance.InstanceMethod(); //Fine
instance.StaticMethod(); //Won't compile

SomeClass.InstanceMethod(); //Won't compile


SomeClass.StaticMethod(); //Fine

The static keyword, when applied to a class, tells the compiler to create a single instance of that
class. It is not then possible to 'new' one or more instance of the class. All methods in a static class
must themselves be declared static.
It is possible, And often desirable, to have static methods of a non-static class. For example a
factory method when creates an instance of a nother class is often declared static as this means that
a particular instance of the class containing the factor method is not required.

Static keyword is widely used to share the same field or method among all the objects of the class.
The actual goal of the static keyword is to share a single data over all the objects.
There are three types of sharing using the static keyword. They are:
•Static Method
•Static Field
•Static Class
Now I am going to give a short brief on these three types.
Static Method
A static method can be accessed from outside the class without creating any object of this class.
This staticmethod can be accessed directly by the name of the static method followed by the . (dot
operator) and the class name.
For example, we can consider the Sqrt method of the Math class. This is how the Sqrt method of the
real Mathclass is defined :
class Math
{
// Do something
public static double Sqrt(double d)
{
// Do something
}
}

From the previous example, you can notify that the Sqrt method is declared as static so that it can be
accessed by using the class name directly, no object of the Math class is required to access
the static method.
So, here I will like to some general properties of a static method:
•It can access only the static fields of the class.
•It can directly invoke the methods that are defined as static.
Static Fields
A static field is shared among all the objects of the of the class. So if an object changes this value,
then all the objects of this class will get the changed value.

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

public Point(int x, int y)


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

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

Now if we create three objects for this class:


Point origin1 = new Point(); // objectCount = 1
Point origin2 = new Point(); // objectCount = 2
Point origin3 = new Point(); // objectCount = 3
Here these three objects share the same field so every time the static field objectCount is
incremented.
Static Class
A static class is used to hold all the utility methods and fields. A static Class has some properties:
•All the methods and fields inside the class must be declared as static.
•A static class cannot contain any instance method or data.
•No object can be created (even using the “new” keyword) of this class.
•It can have a default constructor and it is also static.

Example
Let us consider an example.

Point.cs
using System;
using System.Collections.Generic;
using System.Text;

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

public static int FnObjectCount()


{
return objectCount;
}

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

ConstructorExample.cs
using System;
using System.Collections.Generic;
using System.Text;

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

In this example, the FnObjectCount() method is called directly with the class name, no object is
required here.
If you want to access the static method with an object like:

bottomRight.FnObjectCount() // do not write this


then the compiler will report an error.

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


public static int FnObjectCount()
{
return objectCount;
}
As it is a static method, it can hold only a static field or static method.

Internal Function
The internal access specifier hides its member variables and methods from other
classes and objects, that is resides in other namespace. The variable or classes that are
declared with internal can be access by any member within application. It is the
default access specifiers for a class in C# programming.
using System;

namespace Internal_Access_Specifier
{
class access
{
// String Variable declared as internal
internal string name;
public void print()
{
Console.WriteLine("\nMy name is " + name);
}
}

class Program
{
static void Main(string[] args)
{
access ac = new access();
Console.Write("Enter your name:\t");
// Accepting value in internal variable
ac.name = Console.ReadLine();
ac.print();
Console.ReadLine();
}
}
}

The internal keyword is an access modifier for types and type members. Internal types or members
are accessible only within files in the same assembly, as in this example:
public class BaseClass
{
// Only accessible within the same assembly
internal static int x = 0;
}

Types or members that have access modifier protected internal can be accessed from the current
assembly or from types that are derived from the containing class.
For a comparison of internal with the other access modifiers, see Accessibility Levels (C#
Reference) and Access Modifiers (C# Programming Guide).
For more information about assemblies, see Assemblies and the Global Assembly Cache (C# and
Visual Basic).
A common use of internal access is in component-based development because it enables a group of
components to cooperate in a private manner without being exposed to the rest of the application
code. For example, a framework for building graphical user interfaces could
provide Control and Form classes that cooperate by using members with internal access. Since these
members are internal, they are not exposed to code that is using the framework.
It is an error to reference a type or a member with internal access outside the assembly within which
it was defined.

internal members are visible to all code in the assembly they are declared in.(And to other
assemblies referenced using the [InternalsVisibleTo] attribute)
private members are visible only to the declaring class. (including nested classes)For (hopefully)
obvious reasons, an outer (non-nested) class cannot be declared private.
To answer the question you forgot to ask, protected members are like private members, but are also
visible in all classes that inherit the declaring type. (But only on an expression of at least the type of
the current class)
// Assembly1.cs
// Compile with: /target:library
internal class BaseClass
{
public static int intM = 0;
}

The static constructor will be call the first time an object of the type is instantiated or a static
method is called. And will only run once
The public constructor is accessible to all other types
The internal constructor is only accessible to types in the same assembly
On top of these three there's also protected which is only accessible to types derived from the
enclosing type
and protected internal which is only accessible to types in the same assembly that derives from the
enclosing type
and private which is only accesible from the type it self or any nested types

a static constructor will be called the first time the class is accessed statically.
•a constructor with an internal access modifier can only be called by items that meet the
criteria for internal, which is "accessible only within files in the same assembly".
•a constructor with an public access modifier can be accessed by anything
•and so on. protected and private constructors operate as you expect - the constructors are
accessible to items that meet the criteria for the access modifier.

Sealed Class
Sealed classes are used to restrict the inheritance feature of object oriented programming. Once a class
is defined as a sealed class, the class cannot be inherited.

In C#, the sealed modifier is used to define a class as sealed. In Visual Basic .NET
the NotInheritablekeyword serves the purpose of sealed. If a class is derived from a sealed class then the
compiler throws an error.

If you have ever noticed, structs are sealed. You cannot derive a class from a struct.

The following class definition defines a sealed class in C#:

// Sealed class
sealed class SealedClass
{
}

In the following code, I create a sealed class SealedClass and use it from Class1. If you run
this code then it will work fine. But if you try to derive a class from the SealedClass, you will
get an error.
using System;
class Class1
{
static void Main(string[] args)
{
SealedClass sealedCls = new SealedClass();
int total = sealedCls.Add(4, 5);
Console.WriteLine("Total = " + total.ToString());
}
}
// Sealed class
sealed class SealedClass
{
public int Add(int x, int y)
{
return x + y;
}
}

MSDN Updated

Sealed Methods and Properties

You can also use the sealed modifier on a method or a property that overrides a virtual
method or property in a base class. This enables you to allow classes to derive from your class
and prevent other developers that are using your classes from overriding specific virtual
methods and properties.

class X
{
protected virtual void F() { Console.WriteLine("X.F"); }
protected virtual void F2() { Console.WriteLine("X.F2"); }
}

class Y : X
{
sealed protected override void F() { Console.WriteLine("Y.F"); }
protected override void F2() { Console.WriteLine("X.F3"); }
}

class Z : Y
{
// Attempting to override F causes compiler error CS0239.
// protected override void F() { Console.WriteLine("C.F"); }
// Overriding F2 is allowed.
protected override void F2() { Console.WriteLine("Z.F2"); }
}

Why Sealed Classes?


We just saw how to create and use a sealed class. The main purpose of a sealed class is to
take away the inheritance feature from the user so they cannot derive a class from a sealed
class. One of the best usage of sealed classes is when you have a class with static members.
For example, the "Pens"and "Brushes" classes of the "System.Drawing" namespace.

The Pens class represents the pens for standard colors. This class has only static members. For
example, "Pens.Blue" represents a pen with the blue color. Similarly, the "Brushes" class
represents standard brushes. "Brushes.Blue" represents a brush with blue color.

So when you're designing your application, you may keep in mind that you have sealed classes
to seal the user's boundaries.

In the next article of this series, I will discuss some usage of abstract classes.

Classes can be declared as sealed. This is accomplished by putting the sealed keyword before the
keyword class in the class definition Sealed classes are used to restrict the inheritance feature of
object oriented programming. Once a class is defined as sealed class, this class cannot be inherited.
A sealed class cannot be used as a base class. For this reason, it cannot also be an abstract class.
Sealed classes are primarily used to prevent derivation. Because they can never be used as a base
class, some run-time optimizations can make calling sealed class members slightly faster.

Partial Class
There are several situations when splitting a class definition is desirable:
•When working on large projects, spreading a class over separate files enables multiple
programmers to work on it at the same time.
•When working with automatically generated source, code can be added to the class
without having to recreate the source file. Visual Studio uses this approach when it creates
Windows Forms, Web service wrapper code, and so on. You can create code that uses these
classes without having to modify the file created by Visual Studio.
•To split a class definition, use the partial keyword modifier, as shown here:

public partial class Employee


{
public void DoWork()
{
}
}

public partial class Employee


{
public void GoToLunch()
{
}
}
The partial keyword indicates that other parts of the class, struct, or interface can be defined in the
namespace. All the parts must use the partial keyword. All the parts must be available at compile
time to form the final type. All the parts must have the same accessibility, such as public, private,
and so on.
If any part is declared abstract, then the whole type is considered abstract. If any part is declared
sealed, then the whole type is considered sealed. If any part declares a base type, then the whole
type inherits that class.
All the parts that specify a base class must agree, but parts that omit a base class still inherit the
base type. Parts can specify different base interfaces, and the final type implements all the interfaces
listed by all the partial declarations. Any class, struct, or interface members declared in a partial
definition are available to all the other parts. The final type is the combination of all the parts at
compile time.

The following are merged from all the partial-type definitions:


•XML comments
•interfaces
•generic-type parameter attributes
•class attributes
•members

There are several rules to follow when you are working with partial class definitions:
•All partial-type definitions meant to be parts of the same type must be modified
with partial. For example, the following class declarations generate an error:
public partial class A { }
//public class A { } // Error, must also be marked partial
• The partial modifier can only appear immediately before the keywords class, struct,
or interface.
• Nested partial types are allowed in partial-type definitions as illustrated in the following
example:

partial class ClassWithNestedClass
{
partial class NestedClass { }
}

partial class ClassWithNestedClass


{
partial class NestedClass { }
}
All partial-type definitions meant to be parts of the same type must be defined in the same assembly
and the same module (.exe or .dll file). Partial definitions cannot span multiple modules.
•The class name and generic-type parameters must match on all partial-type
definitions. Generic types can be partial. Each partial declaration must use the same
parameter names in the same order.
•The following keywords on a partial-type definition are optional, but if present on
one partial-type definition, cannot conflict with the keywords specified on another
partial definition for the same type:
•public
•private
•protected
•internal
•abstract
•sealed
•base class
•new modifier (nested parts)
•generic constraints

The biggest use of partial classes is make life easier on code generators / designers. Partial classes
allow the generator to simply emit the code they need to emit and do not have to deal with user edits to
the file. Users are likewise free to annotate the class with new members by having a second partial
class. This provides a very clean framework for separation of concerns.
A better way to look at it is to see how designers functioned before partial classes. The WinForms
designer would spit out all of the code inside of a region with strongly worded comments about not
modifying the code. It had to insert all sorts of heuristics to find the generated code for later processing.
Now it can simply open the designer.cs file and have a high degree of confidence that it contains only
code relative to the designer.

Advantages of a Partial Class


Here is a list of some of the advantages of partial classes:
1.You can separate UI design code and business logic code so that it is easy to read and understand. For
example, you are developing a web application using Visual Studio and add a new web form then there
are two source files, "aspx.cs" and "aspx.designer.cs". These two files have the same class with
the partial keyword. The ".aspx.cs" class has the business logic code while "aspx.designer.cs" has user
interface control definition.
2.When working with automatically generated source, the code can be added to the class without
having to recreate the source file. For example, you are working with LINQ to SQL and create a DBML
file. Now when you drag and drop a table, it creates a partial class in designer.cs and all table
columns have properties in the class. You need more columns in this table to bind on the UI grid but
you don't want to add a new column to the database table so you can create a separate source file for
this class that has a new property for that column and it will be a partial class. So that does affect the
mapping between database table and DBML entity but you can easily get an extra field. It means you
can write the code on your own without messing with the system generated code.
3.More than one developer can simultaneously write the code for the class.
4.You can maintain your application better by compacting large classes. Suppose you have a class that
has multiple interfaces so you can create multiple source files depending on interface implements. It is
easy to understand and maintain an interface implemented on which the source file has a partial class.
Let's see the following code snippet.

Points That You Should be Careful about Partial Classes


There are some points that you should be careful about when you are developing a partial class in
your application.
1.You need to use partial keyword in each part of partial class.
2.The name of each part of partial class should be the same but source file name for each part
of partialclass can be different.
3.All parts of a partial class should be in the same namespace.
4.Each part of a partial class should be in the same assembly or DLL, in other words you can't create
apartial class in source files of a different class library project.
5.Each part of a partial class has the same accessibility.
6.If you inherit a class or interface on a partial class, then it is inherited on all parts of
a partial class.
7.If a part of a partial class is sealed, then the entire class will be sealed.
8.If a part of partial class is abstract, then the entire class will be an abstract class.

Partial Methods
Partial methods are a new feature available in C# 3.0 that don't seem to get enough credit. I think there
was a lot of confusion early on about what partial methods were and how they were used.
Partial methods are intended to solve a major problem that is not only caused by code-generation tools
and also affects those same tools. For instance, you are writing a code-generation tool but want to
provide a way for the developers that are using your generated classes to hook in to specific areas of
the code. As such, you don't want them editing your generated code since those customizations will be
lost the next time the tool runs. On the flip side of this scenario is the developer who needs to write the
code that hooks into those specific areas and doesn't want that code being lost the next time the tool
runs.

Delegates are one solution to this type of problem. In the generated code, you declare a delegate
method that you then call at the appropriate areas. If no one has implemented a concrete version of the
delegate, the call will not do anything. However, if someone has implemented am instance of that
delegate then the call will run the code in that instance. This sounds like a pretty good solution, and,
until partial methods it really was the only solution. The drawback is that the code for the delegate is
always compiled in to the runtime of your application and add to the runtime overhead of application
(granted, that overhead is minimal but it's still there).

Partial classes helped with this problem by allowing the code-generation tools to isolate the generated
code in a partial class. This allowed the developer to add their own methods to the class without fear
that they would be overwritten the next time the tool ran. However, it only helped partially. In order to
accomplish our scenario, you still needed to provide a delegate to allow the developer to hook into your
process.

If we take this a step further and look at partial methods, you will start to see how they work and what
the benefit is of using them. The following rules govern how partials methods can be declared and
used:

1.Must be declared inside a partial class.

2.Must be declared as a void return type.


3.Must be declared with the partial.
4.Cannot be marked as extern.
5.Can be marked static or unsafe.
6.Can be generic.

7.Can have ref but not out parameters.


8.Cannot be referenced as a delegate until they are implemented

9.Cannot have access modifiers such as public, private or internal.


10.Cannot be declared as virtual.
Partial methods are implicitly marked as private. This means they cannot be called from outside the
partial class.

Now that we have the rules out of the way, let's take a look at an example. This is a completely
contrived example, as you typically wouldn't declare both portions of the partial class yourself.

Generics in C#
Generics are the most powerful feature of C# . Generics allow you to define type-safe data structures,
without committing to actual data types. This results in a significant performance boost and higher
quality code, because you get to reuse data processing algorithms without duplicating type-specific
code. In concept, generics are similar to C++ templates, but are drastically different in implementation
and capabilities.
Generics provide the solution to a limitation in earlier versions of the common language
runtime and the C# language in which generalization is accomplished by casting types to and
from the universal base type Object. By creating a generic class, you can create a collection
that is type-safe at compile-time.
The limitations of using non-generic collection classes can be demonstrated by writing a short
program that makes use of the ArrayList collection class from the .NET Framework base class
library. ArrayList is a highly convenient collection class that can be used without modification
to store any reference or value type.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;

namespace Generics
{
class GenericList
{
static void Main(string[] args)
{
// The .NET Framework 1.1 way to create a List
ArrayList list = new ArrayList();

// Add an integer to the List


list.Add(3);

// Add a string to the List. This will compile,


// but may cause a Runtime Error!
list.Add("This will trigger a Runtime Error!");

// We cast to int, but this will causes an InvalidCastException


// when encounter a string in the List.
int t = (int)list[1];

t = 0;
foreach (int x in list)
{
t += x;
}

// The .NET Framework 2.0 way to create a List


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

// No boxing, no casting
list1.Add(3);
list1.Add(1);

// Compile-time error:
list1.Add("This will trigger a Compile-time Error!");

// Get the values from the List, no casting


int t1 = list1[1];

t1 = 0;
foreach (int x in list1)
{
t1 += x;
}
}
}
}

Generics allow you to delay the specification of the data type of programming elements in a class
or a method, until it is actually used in the program. In other words, generics allow you to write a
class or method that can work with any data type.
You write the specifications for the class or the method, with substitute parameters for data types.
When the compiler encounters a constructor for the class or a function call for the method, it
generates code to handle the specific data type. A simple example would help understanding the
concept:
Features of Generics
Using generics is a technique that enriches your programs in the following ways:
•It helps you to maximize code reuse, type safety, and performance.
•You can create generic collection classes. The .NET Framework class library contains several new
generic collection classes in the System.Collections.Generic namespace. You may use these generic
collection classes instead of the collection classes in the System.Collectionsnamespace.
•You can create your own generic interfaces, classes, methods, events and delegates.
•You may create generic classes constrained to enable access to methods on particular data types.
•You may get information on the types used in a generic data type at run-time by means of
reflection.

Introduction to Generic Collections


All the way back in Lesson 02, you learned about arrays and how they allow you to add and retrieve a
collection of objects. Arrays are good for many tasks, but C# v2.0 introduced a new feature called
generics. Among many benefits, one huge benefit is that generics allow us to create collections that allow
us to do more than allowed by an array. This lesson will introduce you to generic collections and how they
can be used. Here are the objectives for this lesson:
•Understand how generic collections can benefit you
•Learn how to create and use a generic List
•Write code that implements a generic Dictionary

What Can Generics Do For Me?


Throughout this tutorial, you've learned about types, whether built-in (int, float, char) or custom
(Shape, Customer, Account). In .NET v1.0 there were collections, such as the ArrayList for working with
groups of objects. An ArrayList is much like an array, except it could automatically grow and offered
many convenience methods that arrays don't have. The problem with ArrayList and all the other .NET
v1.0 collections is that they operate on typeobject. Since all objects derive from the object type, you can
assign anything to an ArrayList. The problem with this is that you incur performance overhead converting
value type objects to and from the object type and a single ArrayList could accidentally hold different
types, which would cause hard to find errors at runtime because you wrote code to work with one type.
Generic collections fix these problems.
A generic collection is strongly typed (type safe), meaning that you can only put one type of object into
it. This eliminates type mismatches at runtime. Another benefit of type safety is that performance is
better with value type objects because they don't incur overhead of being converted to and from
type object. With generic collections, you have the best of all worlds because they are strongly typed, like
arrays, and you have the additional functionality, like ArrayList and other non-generic collections, without
the problems.
The next section will show you how to use a generic List collection.
Creating Generic List<T> Collections
The pattern for using a generic List collection is similar to arrays. You declare the List, populate its
members, then access the members. Here's a code example of how to use a List:
List<int> myInts = new List<int>();

myInts.Add(1);
myInts.Add(2);
myInts.Add(3);

for (int i = 0; i < myInts.Count; i++)


{
Console.WriteLine("MyInts: {0}", myInts[i]);
}

The first thing you should notice is the generic collection List<int>, which is referred to as List of
int. If you looked in the documentation for this class, you would find that it is defined as List<T>,
where T could be any type. For example, if you wanted the list to work
on string or Customer objects, you could define them as List<string> or List<Customer> and they
would hold only string or Customer objects. In the example above, myInts holds only type int.
Using the Add method, you can add as many int objects to the collection as you want. This is
different from arrays, which have a fixed size. TheList<T> class has many more methods you can
use, such as Contains, Remove, and more.
There are two parts of the for loop that you need to know about. First, the condition uses
the Count property of myInts. This is another difference between collections and arrays in that an
array uses a Length property for the same thing. Next, the way to read from a specific position in
theList<T> collection, myInts[i], is the exact same syntax you use with arrays.
The next time you start to use a single-dimension array, consider using a List<T> instead. That said,
be sure to let your solution fit the problem and use the best tool for the job. i.e. it's common to work
with byte[] in many places in the .NET Framework.

IEnumerable and Array, IList and List?


IEnumerable provides only minimal "iterable" functionality. You can traverse the sequence, but
that's about it. This has disadvantages -- for example, it is very inefficient to count elements using
IEnumerable, or to get the nth element -- but it has advantages too -- for example, an IEnumerable
could be an endless sequence, like the sequence of primes.
Array is a fixed-size collection with random access (i.e. you can index into it).
List is a variable-size collection (i.e. you can add and remove elements) with random access.
IList is an interface which abstracts list functionality (count, add, remove, indexer access) away
from the various concrete classes such as List, BindingList, ObservableCollection, etc.

IEnumerable is an interface that allows the iteration through a collection of items (e.g. via the
foreach keyword).
An array is a .NET intrinsic. It holds items of the same type, but it is of a fixed size. Once you
create an array with x elements, it cannot grow or shrink.
IList defines the interface for a list, and also implements IEnumerable.
List implements the IList interface; it is a concrete type of list.
The difference between .NET Lists and arrays is that lists can have elements added to them -- they
grow to be big enough to hold all of the required items. The list stores this internally in an array
and, when the array is no longer big enough to hold all of the elements, a new array is created and
the items copied across.

IList & arrays both implement IEnumerable. That's how interfaces work -- classes implement the
contract and behave in a similar fashion and can be treated similarly as a result (you know that the
class implements IEnumerable, you don't need to know the hows or the whys). I suggest you read
up on interfaces and so forth.

IEnumerable is a general-purpose interface that is used by many classes, such


as Array, Listand String in order to let someone iterate over a collection. Basically, it's what drives
the foreachstatement.
IList is typically how you expose variables of type List to end users. This interface permits random
access to the underlying collection.

IEnumerable

IEnumerable<T> represents a series of items that you can iterate over (using foreach, for example)
IEnumerable doesn't have the Count method and you can't access the collection through an index
(although if you are using LINQ you can get around this with extension methods).
IEnumerable is a general-purpose interface that is used by many classes, such as Array, List and
String in order to let someone iterate over a collection. Basically, it's what drives the foreach
statement.
As a rule of thumb you should always return the type that's highest in the object hierarchy that
works for the consumers of this method. In your case IEnumerable<T>.

IList

IList<T> is a collection that you can add to or remove from.


List has count method and accessed using index.
IList is typically how you expose variables of type List to end users. This interface permits random
access to the underlying collection.
If the consumers of the class need to add elements, access elements by index, remove elements you
are better off using an IList<T>.

HashTable
Hashtable optimizes lookups. It computes a hash of each key you add. It then uses this hash code to
look up the element very quickly. It is an older .NET Framework type. It is slower than the
generic Dictionary type.

using System.Collections;
class Program
{
static Hashtable GetHashtable()
{
// Create and return new Hashtable.
Hashtable hashtable = new Hashtable();
hashtable.Add("Area", 1000);
hashtable.Add("Perimeter", 55);
hashtable.Add("Mortgage", 540);
return hashtable;
}
public static void Main()
{
Hashtable hashtable = GetHashtable();
// See if the Hashtable contains this key.
Console.WriteLine(hashtable.ContainsKey("Perimeter"));
// Test the Contains method. It works the same way.
Console.WriteLine(hashtable.Contains("Area"));
// Get value of Area with indexer.
int value = (int)hashtable["Area"];
// Write the value of Area.
Console.WriteLine(value);
}
}

Dictionary
A dictionary is used where fast lookups are critical. The Dictionary type provides fast lookups with
keys to get values. With it we use keys and values of any type, including ints and strings. Dictionary
requires a special syntax form.
Dictionary is used when we have many different elements. We specify its key type and its value type. It
provides good performance.
class Dict
{
static void Main()
{
// Example Dictionary again
Dictionary<string, int> d = new Dictionary<string, int>()
{
{"Lion", 2}, {"dog", 1}};
// Loop over pairs with foreach
foreach (KeyValuePair<string, int> pair in d)
{
Console.WriteLine ("{0}, {1}",pair.Key, pair.Value);
}
foreach (var pair in d)
{
Console.WriteLine("{0}, {1}", pair.Key, pair.Value);
}
Console.ReadKey();
}
}

Dictionary:
•It returns error if we try to find a key which does not exist.
•It is faster than a Hashtable because there is no boxing and unboxing.
•Only public static members are thread safe.
•Dictionary is a generic type which means we can use it with any data type.

Hashtable:
•It returns null if we try to find a key which does not exist.
•It is slower than dictionary because it requires boxing and unboxing.
•All the members in a Hashtable are thread safe,
•Hashtable is not a generic type,

You use a hashtable (dictionary) when you want fast look up access to an item based on a key.
If you are using List, IList or IEnumerable generally this means that you are looping over data (well
in the case of IEnumerable it definitely means that), and a hashtable isn't going to net you anything.
Now if you were looking up a value in one list and using that to access data in another list, that
would a little different. For example:
1.Find position in list of Item foo.
2.Position in list for foo corresponds to position in another list which contains Foo_Value.
3.Access position in seconds list to get Foo_Value.

Inheritance
Inheritance means parent-child relationship.By using Inheritance methodology we can create a new
class by using existing class code (i.e. reuse existing methods, properties etc).It also referred to as
reusability of the code so by using Inheritance we can reuse the code again and again.

What We Call

In Inheritance main existing class is called as generalized class, base class, super class and parent
class and the new class created from existing class is called as specialized class, sub class, child
class and derived class. We normally talk in terms of base class and derived class.

Syntax of Inheritance
1 class ParentClass{
2
3 ...parent class code
4
5 }
6
7 class ChildClass : ParentClass{
8 ...child class code
9 }
Special Character ":" in Inheritance
Inheritance uses special character called ":" colon to make a relationship between parent and child
as you can see in above syntax of code.

When to Implement Interitance

When we create a new class and we want to reuse some of the methods or properties from existing
class then that is an ideal time to implement inheritance.

Advantage of Interitance

Reusability of the code.


Types of inheritance in c#

There are 5 types of inheritance as shown below.

1.Single Inheritance
2.Multilevel Inheritance
3.Multiple Inheritance
4.Hierarchical Inheritance
5.Hybrid Inheritance
Single Inheritance

Single Inheritance means when a single base is been implemented to single derived class is called as
Single Inheritance.Means we have only one parent class and one child class.

Example of Single Inheritance


01 class Company{
02
03 public void CompanyName(){
04
05 Console.WriteLine("Name of the Company");
06
07 }
08
09 public void CompanyAddress(){
10
11 Console.WriteLine("Address of the Company");
12
13 }
14
15 }
16
17 class Employee : Company {
18
19 public void NameofEmployee(){
20
21 Console.WriteLine("Name of the Employee");
22
23 }
24
25 public void Salary(){
26
27 Console.WriteLine("Salary of the Employee");
28
29 }
30
31 }
As you can see from the above code that we have implemented single inheritance.
Multilevel Inheritance
When a derived class is created from another derived class or let me put it in this way that a class is
created by using another derived class and this type of implementation is called as multilevel
Inheritance

Example of Multilevel Inheritance


1 class HeadOffice{
2
3 public void HeadOfficeAddress(){
4
5 Console.WriteLine("Head Office Address");
6
7 }
8 }
Now let's assume that class "HeadOffice" is our Parent class or Base class. Now in my next step i
will create one derived class.
1 class BranchOffice : HeadOffice{
2
3 public void BranchOfficeAddress(){
4
5 Console.WriteLine("Branch Office Address");
6
7 }
8
9 }
So as you can see that i have created a derived class "BranchOffice" by implementing the class
"HeadOffice" to it.

It means now we have one parent class and one derived class. In the next step i will create another
derived class by implementing our existing derived class "BranchOffice" to achieve multilevel
Inheritance.
01 class Employee : BranchOffice {
02
03 public void NameofEmployee(){
04
05 Console.WriteLine("Name of the Employee");
06
07 }
08
09 public void Salary(){
10
11 Console.WriteLine("Salary of the Employee");
12
13 }
14
15 }
From the above souce code you can see that we have achieved multilevel Inheritance by
implementing one derived class to another derived class. Now the class "Employee" will have the
access of all the properties and methods of class "BranchOffice" and class "HeadOffice".
Multiple Inheritance
Due to the complexity of a code multiple inheritance is not been supported in C# or in DOT.NET
but DOT.NET or C# supports multiple interfaces.
Hierarchical Inheritance
When more than one derived classes are implemented from a same parent class or base class then
that type of implentation is known as hierarchical inheritance.

In short it means single base class having more than one derived classes.

01 class HeadOffice{
02
03 public void HeadOfficeAddress(){
04
05 Console.WriteLine("Head Office Address");
06
07 }
08 }
09
10
11 class BranchOffice1 : HeadOffice{
12
13 public void BranchOfficeAddress(){
14
15 Console.WriteLine("Branch Office Address");
16
17 }
18
19 }
20
21 class BranchOffice2 : HeadOffice{
22
23 public void BranchOfficeAddress(){
24
25 Console.WriteLine("Branch Office Address");
26
27 }
28
29 }
As you can see from above the code that we have one base class "HeadOffice" and two derived
classes "BranchOffice1" and "BranchOffice2" which are implemented from same base class i.e.
"HeadOffice".
Hybrid Inheritance
This is a special type of inheritance and can be achieved from any combination of single,
hierarchical and multi level inheritance known as hybrid inheritance.
In the below code example i have combined hierarchical inheritance and multi level inheritance
together.
01 //This part of code is related to hierarchical inheritance
02 class HeadOffice{
03
04 public void HeadOfficeAddress(){
05
06 Console.WriteLine("Head Office Address");
07
08 }
09 }
10
11
12 class BranchOffice1 : HeadOffice{
13
14 public void BranchOfficeAddress(){
15
16 Console.WriteLine("Branch Office Address");
17
18 }
19
20 }
21
22 class BranchOffice2 : HeadOffice{
23
24 public void BranchOfficeAddress(){
25
26 Console.WriteLine("Branch Office Address");
27
28 }
29
30 }

////This part of code is related to combination of hierarchical inheritance and multi level
01
inheritance
02
03 class Employee : BranchOffice2 {
04
05 public void NameofEmployee(){
06
07 Console.WriteLine("Name of the Employee");
08
09 }
10
11 public void Salary(){
12
13 Console.WriteLine("Salary of the Employee");
14
15 }
16
17 }
So that you have understood the inheritance and their 5 types. Now let's a simple example of
inheritance using csharp.
Example of Inheritance using C#
01 public class Car{
02 private string rearviewmirror;
03 private string gear;
04 private string clutch;
05 private string steering;
06
07 public string RearViewMirror
08 {
09 get { return rearviewmirror; }
10 set { rearviewmirror = value; }
11 }
12
13 public string Gear
14 {
15 get { return gear; }
16 set { gear = value; }
17 }
18
19 public string Clutch
20 {
21 get { return clutch; }
22 set { clutch = value; }
23 }
24
25 public string Steering
26 {
27 get { return steering; }
28 set { steering = value; }
29 }
30
31 public virtual void CarPrice()
32 {
33 Console.WriteLine("Car Prize is : 0");
34 }
35
36 public virtual void NameofCar()
37 {
38 Console.WriteLine("Company Name of this Car is -- ");
39 }
40
41
42 }
Above i have created a simple class "Car" with some methods and some properties. Now next step i
will create two classes "SentroCar" and "BCWCar" and implement it with a single base class "Car"

Derived Class 1 implemented with base class Car


01 public class SentroCar:Car
02 {
03
04 public override void CarPrice()
05 {
06 Console.WriteLine("Car Prize is : 2.5L INR");
07 }
08 public override void NameofCar()
09 {
10 Console.WriteLine("Company Name of this Car is Sentro");
11 }
12 }
Derived Class 2 implemented with base class Car

01 public class BCWCar : Car


02 {
03
04 public override void CarPrice()
05 {
06 Console.WriteLine("Car Prize is : 4.5L INR");
07 }
08 public override void NameofCar()
09 {
10 Console.WriteLine("Company Name of this Car is BCW ");
11 }
12 }
As you see that we have two derived classes implemented from same base class. This type of
implementation can also be called as Hierarchical Inheritance.
Output by Using Console Application
01 class Program
02 {
03 static void Main(string[] args)
04 {
05
06 Car obj = new SentroCar();
07 obj.CarPrice();
08 obj.NameofCar();
09
10 Car obj = new BCWCar();
11 obj.CarPrice();
12 obj.NameofCar();
13 }
14 }
//Output
Car Prize is : 2.5L INR
Company Name of this Car is Sentro

Car Prize is : 4.5L INR


Company Name of this Car is BCW.

What are the main components of .NET Framework?

.NET Framework provides enormous advantages to software developers in comparison to the advantages
provided by other platforms. Microsoft has united various modern as well as existing technologies of
software development in .NET Framework. These technologies are used by developers to develop highly
efficient applications for modern as well as future business needs. The following are the key components
of .NET Framework:

• .NET Framework Class Library


• Common Language Runtime
• Dynamic Language Runtimes (DLR)
• Application Domains
• Runtime Host
• Common Type System
• Metadata and Self-Describing Components
• Cross-Language Interoperability
• .NET Framework Security
• Profiling
• Side-by-Side Execution
List the new features added in .NET Framework 4.0.

The following are the new features of .NET Framework 4.0:

• Improved Application Compatibility and Deployment Support


• Dynamic Language Runtime
• Managed Extensibility Framework
• Parallel Programming framework
• Improved Security Model
• Networking Improvements
• Improved Core ASP.NET Services
• Improvements in WPF 4
• Improved Entity Framework (EF)
• Integration between WCF and WF
What is an IL?

Intermediate Language is also known as MSIL (Microsoft Intermediate Language) or CIL (Common
Intermediate Language). All .NET source code is compiled to IL. IL is then converted to machine code at
the point where the software is installed, or at run-time by a Just-In-Time (JIT) compiler.
What is Manifest?

Assembly metadata is stored in Manifest. Manifest contains all the metadata needed to do the following
things

• Version of assembly.
• Security identity.
• Scope of the assembly.
• Resolve references to resources and classes.

The assembly manifest can be stored in a PE file either (an .exe or) .dll with Microsoft
intermediate language (MSIL code with Microsoft intermediate language (MSIL) code or in a
stand-alone PE file, that contains only assembly manifest information.

What are code contracts?

Code contracts help you to express the code assumptions and statements stating the behavior of your
code in a language-neutral way. The contracts are included in the form of pre-conditions, post-conditions
and object-invariants. The contracts help you to improve-testing by enabling run-time checking, static
contract verification, and documentation generation.

The System.Diagnostics.Contracts namespace contains static classes that are used to express
contracts in your code.
Name the classes that are introduced in the System.Numerics namespace.

The following two new classes are introduced in the System.Numerics namespace:

• BigInteger - Refers to a non-primitive integral type, which is used to hold a value of any size.
It has no lower and upper limit, making it possible for you to perform arithmetic calculations with
very large numbers, even with the numbers which cannot hold by double or long.
• Complex - Represents complex numbers and enables different arithmetic operations with
complex numbers. A number represented in the form a + bi, where a is the real part, and b is
the imaginary part, is a complex number.

What is Common Type System (CTS)?

CTS is the component of CLR through which .NET Framework provides support for multiple languages
because it contains a type system that is common across all the languages. Two CTS-compliant
languages do not require type conversion when calling the code written in one language from within the
code written in another language. CTS provide a base set of data types for all the languages supported
by.NET Framework. This means that the size of integer and long variables is same across all .NET-
compliant programming languages. However, each language uses aliases for the base data types provided
by CTS. For example, CTS uses the data type system. int32 to represent a 4 byte integer value; however,
Visual Basic uses the alias integer for the same; whereas, C# uses the alias int. This is done for the sake
of clarity and simplicity.

Which method do you use to enforce garbage collection in .NET?


The System.GC.Collect() method.
State the differences between the Dispose() and Finalize().

CLR uses the Dispose and Finalize methods to perform garbage collection of run-time objects of .NET
applications.

The Finalize method is called automatically by the runtime. CLR has a garbage collector (GC), which
periodically checks for objects in heap that are no longer referenced by any object or program. It calls
the Finalize method to free the memory used by such objects. The Dispose method is called by the
programmer.Dispose is another method to release the memory used by an object. The Dispose method
needs to be explicitly called in code to dereference an object from the heap. The Dispose method can be
invoked only by the classes that implement the IDisposable interface.

What is code access security (CAS)?

Code access security (CAS) is part of the .NET security model that prevents unauthorized access of
resources and operations, and restricts the code to perform particular tasks.

Differentiate between managed and unmanaged code?

Managed code is the code that is executed directly by the CLR instead of the operating system. The code
compiler first compiles the managed code to intermediate language (IL) code, also called as MSIL code.
This code doesn't depend on machine configurations and can be executed on different machines.

Unmanaged code is the code that is executed directly by the operating system outside the CLR
environment. It is directly compiled to native machine code which depends on the machine configuration.
In the managed code, since the execution of the code is governed by CLR, the runtime provides different
services, such as garbage collection, type checking, exception handling, and security support. These
services help provide uniformity in platform and language-independent behavior of managed code
applications. In the unmanaged code, the allocation of memory, type safety, and security is required to
be taken care of by the developer. If the unmanaged code is not properly handled, it may result in
memory leak. Examples of unmanaged code are ActiveX components and Win32 APIs that execute
beyond the scope of native CLR.

What are tuples?

Tuple is a fixed-size collection that can have elements of either same or different data types. Similar to
arrays, a user must have to specify the size of a tuple at the time of declaration. Tuples are allowed to
hold up from 1 to 8 elements and if there are more than 8 elements, then the 8th element can be defined
as another tuple. Tuples can be specified as parameter or return type of a method.

How can you turn-on and turn-off CAS?

YOU can use the Code Access Security Tool (Caspol.exe) to turn security on and off.

To turn off security, type the following command at the command prompt:
caspol -security off

To turn on security, type the following command at the command prompt:


caspol -security on

In the .NET Framework 4.0, for using Caspol.exe, you first need to set
the <LegacyCasPolicy> element totrue.

What is garbage collection? Explain the difference between garbage collections in .NET 4.0 and
earlier versions.

Garbage collection prevents memory leaks during execution of programs. Garbage collector is a low-
priority process that manages the allocation and deallocation of memory for your application. It checks
for the unreferenced variables and objects. If GC finds any object that is no longer used by the
application, it frees up the memory from that object.
GC has changed a bit with the introduction of .NET 4.0. In .NET 4.0, the GC.Collect() method contains
the following overloaded methods:

GC.Collect(int)

GC.Collect(int, GCCollectionMode)

Another new feature introduced in .NET is to notify you when the GC.Collect() method is invoked and
completed successfully by using different methods. The .NET 4.0 supports a new background garbage
collection that replaces the concurrent garbage collection used in earlier versions. This concurrent GC
allocates memory while running and uses current segment (which is 16 MB on a workstation) for that.
After that, all threads are suspended. In case of background GC, a separate ephemeral GC - gen0 and
gen1 can be started, while the full GC - gen0, 1, and 2 - is already running.

How does CAS works?

There are two key concepts of CAS security policy- code groups and permissions. A code group contains
assemblies in it in a manner that each .NET assembly is related to a particular code group and some
permissions are granted to each code group. For example, using the default security policy, a control
downloaded from a Web site belongs to the Zone, Internet code group, which adheres to the permissions
defined by the named permission set. (Normally, the named permission set represents a very restrictive
range of permissions.)

Assembly execution involves the following steps:

1. Evidences are gathered about assembly.


2. Depending on the gathered evidences, the assembly is assigned to a code group.
3. Security rights are allocated to the assembly, depending on the code group.
4. Assembly runs as per the rights assigned to it.

5.
What is Difference between NameSpace and Assembly?

Following are the differences between namespace and assembly:

• Assembly is physical grouping of logical units, Namespace, logically groups classes.


• Namespace can span multiple assembly.

Mention the execution process for managed code.

A piece of managed code is executed as follows:

• Choosing a language compiler


• Compiling the code to MSIL
• Compiling MSIL to native code
• Executing the code.
How can you instantiate a tuple?

The following are two ways to instantiate a tuple:

• Using the new operator. For example,

Tuple<String, int> t = new Tuple<String, int> ("Hellow", 2);

• Using the Create factory method available in the Tuple class. For example,
Tuple<int, int, int> t = Tuple.Create<int, int, int> (2, 4, 5);

What is Microsoft Intermediate Language (MSIL)?

The .NET Framework is shipped with compilers of all .NET programming languages to develop programs.
There are separate compilers for the Visual Basic, C#, and Visual C++ programming languages in .NET
Framework. Each .NET compiler produces an intermediate code after compiling the source code. The
intermediate code is common for all languages and is understandable only to .NET environment. This
intermediate code is known as MSIL.
What is lazy initialization?

Lazy initialization is a process by which an object is not initialized until it is first called in your code.
The .NET 4.0 introduces a new wrapper class, System.Lazy<T>, for executing the lazy initialization in
your application. Lazy initialization helps you to reduce the wastage of resources and memory
requirements to improve performance. It also supports thread-safety.
How many types of generations are there in a garbage collector?

Memory management in the CLR is divided into three generations that are build up by grouping memory
segments. Generations enhance the garbage collection performance. The following are the three types of
generations found in a garbage collector:

• Generation 0 - When an object is initialized, it is said to be in generation 0.


• Generation 1 - The objects that are under garbage collection process are considered to be in
generation 1.
• Generation 2 - Whenever new objects are created and added to the memory, they are added to
generation 0 and the old objects in generation 1 are considered to be in generation 2.

What is Common Language Specification (CLS)?

CLS is a set of basic rules, which must be followed by each .NET language to be a .NET- compliant
language. It enables interoperability between two .NET-compliant languages. CLS is a subset of CTS;
therefore, the languages supported by CLS can use each other's class libraries similar to their own.
Application programming interfaces (APIs), which are designed by following the rules defined in CLS can
be used by all .NET-compliant languages.

What is the role of the JIT compiler in .NET Framework?

The JIT compiler is an important element of CLR, which loads MSIL on target machines for execution. The
MSIL is stored in .NET assemblies after the developer has compiled the code written in any .NET-
compliant programming language, such as Visual Basic and C#.

JIT compiler translates the MSIL code of an assembly and uses the CPU architecture of the target
machine to execute a .NET application. It also stores the resulting native code so that it is accessible for
subsequent calls. If a code executing on a target machine calls a non-native method, the JIT compiler
converts the MSIL of that method into native code. JIT compiler also enforces type-safety in runtime
environment of .NET Framework. It checks for the values that are passed to parameters of any method.

For example, the JIT compiler detects any event, if a user tries to assign a 32-bit value to a parameter
that can only accept 8-bit value.

What is difference between System.String and System.StringBuilder classes?

String and StringBuilder classes are used to store string values but the difference in them is that
String is immutable (read only) by nature, because a value once assigned to a String object cannot be
changed after its creation. When the value in the String object is modified, a new object is created, in
memory, with a new value assigned to the String object. On the other hand, the StringBuilder class
is mutable, as it occupies the same space even if you change the value. The StringBuilder class is
more efficient where you have to perform a large amount of string manipulation.

Describe the roles of CLR in .NET Framework.

CLR provides an environment to execute .NET applications on target machines. CLR is also a common
runtime environment for all .NET code irrespective of their programming language, as the compilers of
respective language in .NET Framework convert every source code into a common language known as
MSIL or IL (Intermediate Language).

CLR also provides various services to execute processes, such as memory management service and
security services. CLR performs various tasks to manage the execution process of .NET applications.

The responsibilities of CLR are listed as follows:

• Automatic memory management


• Garbage Collection
• Code Access Security
• Code verification
• JIT compilation of .NET code

What is the difference between int and int32.


There is no difference between int and int32. System.Int32 is a .NET Class and int is an alias name
forSystem.Int32.

ASP.NET
Concept of Postback in ASP.NET?
A postback is a request sent from a client to server from the same page user is already working with.
ASP.NET was introduced with a mechanism to post an HTTP POST request back to the same page. It's
basically posting a complete page back to server (i.e. sending all of its data) on same page. So, the
whole page is refreshed.
Another concept related to this approach is "Callback" that is also asked sometimes during a technical
interview question. Click here to understand Postback Vs Callback in ASP.NET.

ASP.NET Page life Cycle


PreInit:
You can:
•Check for the IsPostBack property to determine whether this is the first time the page is being processed.
•Create or recreate dynamic controls.
•Set master page dynamically.
•Set the Theme property dynamically.
•Read or set profile property values.
If Request is postback:
•The values of the controls have not yet been restored from view state.
•If you set control property at this stage, its value might be overwritten in the next event.

Init:
•In the Init event of the individual controls occurs first, later the Init event of the Page takes place.
•This event is used to initialize control properties.
InitComplete:
•Tracking of the ViewState is turned on in this event.
•Any changes made to the ViewState in this event are persisted even after the next postback.

PreLoad:
•This event processes the postback data that is included with the request.

Load:
•In this event the Page object calls the OnLoad method on the Page object itself, later the OnLoad method of the
controls is called.
•Thus Load event of the individual controls occurs after the Load event of the page.

ControlEvents:
•This event is used to handle specific control events such as a Button control’s Click event or
a TextBoxcontrol’s TextChanged event.
In case of postback:
•If the page contains validator controls, the Page.IsValid property and the validation of the controls takes place
before the firing of individual control events.

LoadComplete:
•This event occurs after the event handling stage.
•This event is used for tasks such as loading all other controls on the page.

PreRender:
•In this event the PreRender event of the page is called first and later for the child control.
Usage:
•This method is used to make final changes to the controls on the page like assigning the DataSourceId and
calling the DataBind method.

PreRenderComplete:
•This event is raised after each control's PreRender property is completed.

SaveStateComplete:
•This is raised after the control state and view state have been saved for the page and for all controls.

RenderComplete:
•The page object calls this method on each control which is present on the page.
•This method writes the control’s markup to send it to the browser.

Unload:
•This event is raised for each control and then for the Page object.
Usage:
•Use this event in controls for final cleanup work, such as closing open database connections, closing open files,
etc.

Section Event Description


HttpModule BeginRequest This event signals a new request; it is guaranteed to
Section Event Description
be raised on each request.
This event signals that ASP.NET runtime is ready to
HttpModule AuthenticateRequest authenticate the user. Any authentication code can
be injected here.
This event signals that ASP.NET runtime is ready to
HttpModule AuthorizeRequest authorize the user. Any authorization code can be
injected here.
In ASP.NET, we normally use outputcache directive to
do caching. In this event, ASP.NET runtime
HttpModule ResolveRequestCache determines if the page can be served from the cache
rather than loading the patch from scratch. Any
caching specific activity can be injected here.
This event signals that ASP.NET runtime is ready to
HttpModule AcquireRequestState acquire session variables. Any processing you would
like to do on session variables.
This event is raised just prior to handling control to
the HttpHandler. Before you want the control to be
HttpModule PreRequestHandlerExecute
handed over to the handler any pre-processing you
would like to do.
Httphandler logic is executed. In this section, we
HttpHandler ProcessRequest will write logic which needs to be executed as per
page extensions.
This event happens in the ASP.NET page and can be
used for:
Creating controls dynamically, in case you have
controls to be created on runtime.
Page Init
Any setting initialization.
Master pages and the settings.
In this section, we do not have access to viewstate,
postedvalues and neither the controls are initialized.
In this section, the ASP.NET controls are fully loaded
Page Load and you write UI manipulation logic or any other
logic over here.
If you have valuators on your page, you would like to
Page Validate
check the same here.
It’s now time to send the output to the browser. If
you would like to make some changes to the final
Render
HTML which is going out to the browser, you can
enter your HTML logic here.
Page Unload Page object is unloaded from the memory.
Any logic you would like to inject after the handlers
HttpModule PostRequestHandlerExecute
are executed.
If you would like to save update some state variables
HttpModule ReleaserequestState
like session variables.
HttpModule UpdateRequestCache Before you end, if you want to update your cache.
This is the last stage before your output is sent to the
HttpModule EndRequest
client browser.
Stage Description
The page request occurs before the page life cycle begins. When the page is
requested by a user, ASP.NET determines whether the page needs to be parsed
Page request
and compiled (therefore beginning the life of a page), or whether a cached
version of the page can be sent in response without running the page.
In the start stage, page properties such as Request and Response are set. At this
stage, the page also determines whether the request is a postback or a new
Start
request and sets the IsPostBack property. The page also sets
the UICulture property.
During page initialization, controls on the page are available and each
control's UniqueID property is set. A master page and themes are also applied
Initialization to the page if applicable. If the current request is a postback, the postback data
has not yet been loaded and control property values have not been restored to
the values from view state.
During load, if the current request is a postback, control properties are loaded
Load
with information recovered from view state and control state.
If the request is a postback, control event handlers are called. After that,
Postback the Validate method of all validator controls is called, which sets
event the IsValidproperty of individual validator controls and of the page. (There is
handling an exception to this sequence: the handler for the event that caused validation
is called after validation.)
Before rendering, view state is saved for the page and all controls. During the
rendering stage, the page calls the Render method for each control, providing a
Rendering
text writer that writes its output to the OutputStream object of the
page's Response property.
The Unload event is raised after the page has been fully rendered, sent to the
Unload client, and is ready to be discarded. At this point, page properties such
asResponse and Request are unloaded and cleanup is performed.

State management?
Web is Stateless. It means a new instance of the web page class is re-created each time the page is
posted to the server. As we all know HTTP is a stateless protocol, its can't holds the client
information on page. As for example , if we enter a text and client on submit button, text does not
appear after post back , only because of page is recreated on its round trip.
As given in above pages, page is recreated before its comes to clients and happened for each and
every request. So it is a big issue to maintain the state of the page and information for a web
application. That is the reason to start concept of State Management. To overcome this problem
ASP.NET 2.0 Provides some features like View State, Cookies, Session, Application objects etc. to
manage the state of page.
There are some few selection criteria to selected proper way to maintain the state, as there are many
way to do that. Those criteria are:
•How much information do you need to store?
•Does the client accept persistent or in-memory cookies?
•Do you want to store the information on the client or on the server?
•Is the information sensitive?
•What performance and bandwidth criteria do you have for your application?
•What are the capabilities of the browsers and devices that you are targeting?
•Do you need to store information per user?
•How long do you need to store the information?
•Do you have a Web farm (multiple servers), a Web garden (multiple processes on one machine), or
a single process that serves the application?
So, when ever you start to think about state management, you should think about above criteria.
based on that you can choose the best approaches for manages state for your web application.
Different types of state management?
There are two different types of state management:
1.Client Side State Management
• View State
• Hidden Field
• Cookies
• Control State
2.Server Side State Management
• Session
• Application Object
• Caching
• Database
Client Side state management does not use any server resource , it store information using client
side option. Server Side state management use server side resource for store data. Selection of client
side and server side state management should be based on your requirements and the selection
criteria that are already given.
What is view state?
View State is one of the most important and useful client side state management mechanism. It can
store the page value at the time of post back (Sending and Receiving information from Server) of
your page. ASP.NET pages provide the ViewState property as a built-in structure for automatically
storing values between multiple requests for the same page.
Example:
If you want to add one variable in View State,
Collapse | Copy Code
ViewState["Var"]=Count;
For Retrieving information from View State
Collapse | Copy Code
string Test=ViewState["TestVal"];
Sometimes you may need to typecast ViewState Value to retreive. As I give an Example to strore
and retreive object in view state in the last of this article.
Advantages of view state?
This are the main advantage of using View State:
•Easy to implement
•No server resources are required
•Enhanced security features ,like it can be encoded and compressed.
Disadvantages of view state?
This are the main disadvantages of using View State:
•It can be performance overhead if we are going to store larger amount of data , because it is
associated with page only.
•Its stored in a hidden filed in hashed format (which I have discussed later) still it can be easily
trapped.
•It does not have any support on mobile devices.
When we should use view state?
I already describe the criteria of selecting State management. A few point you should remember
when you select view state for maintain your page state.
•Size of data should be small , because data are bind with page controls , so for larger amount of
data it can be cause of performance overhead.
•Try to avoid storing secure data in view state
When we should avoid view state?
You won't need view state for a control for following cases,
•The control never change
•The control is repopulated on every postback
•The control is an input control and it changes only of user actions.
Where is view state stored?
View State stored the value of page controls as a string which is hashed and encoded in some
hashing and encoding technology. It only contain information about page and its controls. Its does
not have any interaction with server. It stays along with the page in the Client Browser. View State
use Hidden field to store its information in a encoding format.
Suppose you have written a simple code , to store a value of control:
Collapse | Copy Code
ViewState["Value"] = MyControl.Text;
Now, Run you application, In Browser, RighClick > View Source , You will get the following
section of code
Fig : View state stored in hidden field
Now , look at the value. looks likes a encrypted string, This is Base64 Encoded string, this is not a
encoded string. So it can easily be decoded. Base64 makes a string suitable for HTTP transfer plus
it makes it a little hard to read . Read More about Base64 Encoding . Any body can decode that
string and read the original value. so be careful about that. There is a security lack of view state.
How to store object in view state?
We can store an object easily as we can store string or integer type variable. But what we need ? we
need to convert it into stream of byte. because as I already said , view state store information in
hidden filed in the page. So we need to use Serialization. If object which we are trying to store in
view state ,are not serializable , then we will get a error message .
Just take as example,
Collapse | Copy Code
//Create a simple class and make it as Serializable
[Serializable]
public class student
{
public int Roll;
public string Name;
public void AddStudent(int intRoll,int strName)
{
this.Roll=intRoll;
this.Name=strName;
}
}

Now we will try to store object of "Student" Class in a view state.


Collapse | Copy Code
//Store Student Class in View State
student _objStudent = new student();
_objStudent.AddStudent(2, "Abhijit");
ViewState["StudentObject"] = _objStudent;

//Retrieve Student information view state


student _objStudent;
_objStudent = (student)ViewState["StudentObject"];
How to trace your view state information?
If you want to trace your view state information, by just enable "Trace" option of Page Directive
Now Run your web application, You can view the details of View State Size along with control ID
in Control TreeSection. Don't worry about "Render Size Byte" , this only the size of rendered
control.
Fig : View State Details
Enabling and Disabling View State
You can enable and disable View state for a single control as well as at page level also. To turnoff
view state for a single control , set EnableViewState Property of that control to false. e.g.:
Collapse | Copy Code
TextBox1.EnableViewState =false;

To turnoff the view state of entire page, we need to set EnableViewState to false of Page Directive
as shown bellow.
Even you disable view state for the entire page , you will see the hidden view state tag with a small
amount of information, ASP.NET always store the controls hierarchy for the page at minimum ,
even if view state is disabled.
For enabling the same, you have to use the same property just set them as True
as for example, for a single control we can enabled view state in following way,
Collapse | Copy Code
TextBox1.EnableViewState =true;

and for a page level,

How to make view state secure?


As I already discuss View state information is stored in a hidden filed in a form of Base64
Encoding String, and it looks like:
Fig : View state stored in hidden field
Many of ASP.NET Programmers assume that this is an Encrypted format, but I am saying it again,
that this is not a encrypted string. It can be break easily. To make your view state secure, There are
two option for that,
•First, you can make sure that the view state information is tamper-proof by using "hash code". You
can do this by adding "EnableViewStateMAC=true" with your page directive. MAC Stands
for "Message Authentication Code"
A hash code , is a cryptographically strong checksum, which is calculated by ASP.NET and its
added with the view state content and stored in hidden filed. At the time of next post back, the
checksum data again verified , if there are some mismatch, Post back will be rejected. we can set
this property to web.config file also.
•Second option is to set ViewStateEncryptionMode="Always" with your page directives, which
will encrypt the view state data. You can add this in following way
It ViewStateEncryptionMode has three different options to set:
•Always
•Auto
•Never
Always, mean encrypt the view state always, Never means, Never encrypt the view state data
and Auto Says , encrypt if any control request specially for encryption. For auto , control must
callPage.RegisterRequiresViewStateEncryption() method for request encryption.
we can set the Setting for
"EnableViewStateMAC" and ViewStateEncryptionMode" in web.config also.
Note : Try to avoid View State Encryption if not necessary , because it cause the performance issue.

What is AutoPostBack?

If you want a control to postback automatically when an event is raised, you need to set
the AutoPostBackproperty of the control to True.

What is the function of the ViewState property?


The ASP.NET 4.0 introduced a new property called ViewStateMode for the Control class. Now you can
enable the view state to an individual control even if the view state for an ASP.NET page is disabled.

Why do you use the App_Code folder in ASP.NET?

The App_Code folder is automatically present in the project. It stores the files, such as classes, typed
data set, text files, and reports. If this folder is not available in the application, you can add this folder.
One of the important features of the App_Code folder is that only one dll is created for the complete
folder, irrespective of how many files it contains.

What is IIS? Why is it used?

Internet Information Services (IIS) is created by Microsoft to provide Internet-based services to ASP.NET
Web applications. It makes your computer to work as a Web server and provides the functionality to
develop and deploy Web applications on the server. IIS handles the request and response cycle on the
Web server. It also offers the services of SMTP and FrontPage server extensions. The SMTP is used to
send emails and use FrontPage server extensions to get the dynamic features of IIS, such as form
handler.
What is Query String? What are its advantages and limitations?

The Query String helps in sending the page information to the server.

The Query String has the following advantages:

• Every browser works with Query Strings.


• It does not require server resources and so does not exert any kind of burden on the server.

The following are the limitations of Query String:


• Information must be within the limit because URL does not support many chara

• Information is clearly visible to the user, which leads to security threats.

What is tracing? Where is it used?

Tracing displays the details about how the code was executed. It refers to collecting information about
the application while it is running. Tracing information can help you to troubleshoot an application. It
enables you to record information in various log files about the errors that might occur at run time. You
can analyze these log files to find the cause of the errors.

In .NET, we have objects called Trace Listeners. A listener is an object that gets the trace output and
stores it to different places, such as a window, a file on your locale drive, or a SQL Server.

The System.Diagnostics namespace contains the predefined interfaces, classes, and structures that
are used for tracing. It supplies two classes, Trace and Debug, which allow you to write errors and logs
related to the application execution. Trace listeners are objects that collect the output of tracing
processes.

What is the difference between authentication and authorization?

Authentication verifies the identity of a user and authorization is a process where you can check whether
or not the identity has access rights to the system. In other words, you can say that authentication is a
procedure of getting some credentials from the users and verify the user's identity against those
credentials. Authorization is a procedure of granting access of particular resources to an authenticated
user. You should note that authentication always takes place before authorization.

Differentiate globalization and localization.

The globalization is a technique to identify the specific part of a Web application that is different for
different languages and make separate that portion from the core of the Web application. The localization
is a procedure of configuring a Web application to be supported for a specific language or locale.
What is ViewState?

The ViewState is a feature used by ASP.NET Web page to store the value of a page and its controls just
before posting the page. Once the page is posted, the first task by the page processing is to restore
the ViewState to get the values of the controls.

How can you send an email message from an ASP.NET Web page?
You can use the System.Net.Mail.MailMessage and the System.Net.Mail.SmtpMail classes to
send an email in your Web pages. In order to send an email through your mail server, you need to create
an object of the SmtpClient class and set the server name, port, and credentials.

What is the difference between


the Response.Write() and Response.Output.Write() methods?

The Response.Write() method allows you to write the normal output; whereas,
theResponse.Output.Write() method allows you to write the formatted output.

Differentiate between client-side and server-side validations in Web pages.

Client-side validations take place at the client end with the help of JavaScript and VBScript before the
Web page is sent to the server. On the other hand, server-side validations take place at the server end.

What are HTTP handlers in ASP.NET?

HTTP handlers, as the name suggests, are used to handle user requests for Web application resources.
They are the backbone of the request-response model of Web applications. There is a specific event
handler to handle the request for each user request type and send back the corresponding response
object.

Each user requests to the IIS Web server flows through the HTTP pipeline, which refers to a series of
components (HTTP modules and HTTP handlers) to process the request. HTTP modules act as filters to
process the request as it passes through the HTTP pipeline. The request, after passing through the HTTP
modules, is assigned to an HTTP handler that determines the response of the server to the user request.
The response then passes through the HTTP modules once again and is then sent back to the user.

You can define HTTP handlers in the <httpHandlers> element of a configuration file.
The <add> element tag is used to add new handlers and the <remove> element tag is used to remove
existing handlers. To create an HTTP handler, you need to define a class that implements
the IHttpHandler interface.

What are the events that happen when a client requests an ASP.NET page from IIS server?

The following events happen when a client requests an ASP.NET page from the IIS server:

1. User requests for an application resource.


2. The integrated request-processing pipeline receives the first user request.
3. Response objects are created for each user request.
4. An object of the HttpApplication class is created and allocated to the Request object.
5. The HttpApplication class processes the user request.

What are the event handlers that can be included in the Global.asax file?
The Global.asax file contains some of the following important event handlers:

• Application_Error
• Application_Start
• Application_End
• Session_Start
• Session_End
Make a list of all templates of the Repeater control.

The Repeater control contains the following templates:

• ItemTemplate
• AlternatingltemTemplate
• SeparatorTemplate
• HeaderTemplate
• FooterTemplate
Describe the complete lifecycle of a Web page.

When we execute a Web page, it passes from the following stages, which are collectively known as Web
page lifecycle:

• Page request - During this stage, ASP.NET makes sure the page either parsed or compiled and a
cached version of the page can be sent in response
• Start - During this stage sets the Request and Response page properties and the page check the
page request is either a postback or a new request
• Page Initialization - During this stage, the page initialize and the control's Unique Id property
are set
• Load - During this stage, if the request is postback, the control properties are loaded without
loading the view state and control state otherwise loads the view state
• Validation - During this stage, the controls are validated
• Postback event handling - During this stage, if the request is a postback, handles the event
• Rendering - During this stage, the page invokes the Render method to each control for return
the output
• Unload - During this stage, when the page is completely rendered and sent to the client, the
page is unloaded.

What is a Cookie? Where is it used in ASP.NET?


Cookie is a lightweight executable program, which the server posts to client machines. Cookies store the
identity of a user at the first visit of the Web site and validate them later on the next visits for their
authenticity. The values of a cookie can be transferred between the user's request and the server's
response.

What is the difference between adding items into cache through the Add() method and
through theInsert() method?

Both methods work in a similar way except that the Cache.Add() function returns an object that
represents the item you added in the cache. The Cache.Insert() function can replace an existing item
in the cache, which is not possible using the Cache.Add() method.

Explain the cookie less session and its working.

ASP.NET manages the session state in the same process that processes the request and does not create a
cookie. It is known as a cookie less session. If cookies are not available, a session is tracked by adding a
session identifier to the URL. The cookie less session is enabled using the following code
snippet:<sessionState cookieless="true" />

What is a round trip?

The trip of a Web page from the client to the server and then back to the client is known as a round trip.

What are the major built-in objects in ASP.NET?

The major built-in objects in ASP.NET are as follows:


• Application
• Request
• Response
• Server
• Session
• Context
• Trace

What is the appSettings Section in the web.config file?

The web.config file sets the configuration for a Web project. The appSettings block in configuration
file sets the user-defined values for the whole application.

For example, in the following code snippet, the specified ConnectionString section is used throughout
the project for database connection:

<configuration>
<appSettings>
<add key="ConnectionString" value="server=indiabixserver; pwd=dbpassword;
database=indiabix" />
</appSettings>
...
What does the "EnableViewState" property do? Why do we want it On or Off?

The EnableViewState property enables the ViewState property on the page. It is set to On to allow
the page to save the users input between postback requests of a Web page; that is, between
the Request and corresponding Response objects. When this property is set to Off, the page does not
store the users input during postback.

Which event determines that all the controls are completely loaded into memory?
The Page_Load event determines that all the controls on the page are fully loaded. You can also access
the controls in the Page_Init event; however, the ViewState property does not load completely during
this event.

What is Role-based security?

In the Role-based security, you can assign a role to every user and grant the privilege according to that
role. A role is a group of principal that restricts a user's privileges. Therefore, all the organization and
applications use role-based security model to determine whether a user has enough privileges to perform
a requested task.

What are the HTML server controls in ASP.NET?

HTML server controls are similar to the standard HTML elements, which are normally used in HTML pages.
They expose properties and events that can be used programmatically. To make these controls
programmatically accessible, you need to specify that the HTML controls act as a server control by adding
the runat="server"attribute.

Why a SiteMapPath control is referred to as breadcrumb or eyebrow navigation control?

The SiteMapPath control displays a hierarchical path to the root Web page of the Web site. Therefore, it
is known as the breadcrumb or eyebrow navigation control.

Which namespaces are necessary to create a localized application?


The System.Globalization and System.Resources namespaces are essential to develop a localized
application.

What is the difference between an HtmlInputCheckBox control and


an HtmlInputRadioButton control?

You can select more than one HtmlInputCheckBox control from a group
of HtmlInputCheckBox controls; whereas, you can select only a
single HtmllnputRadioButton control from a group ofHtmlInputRadioButton controls.

Explain the AdRotator Control.

The AdRotator is an ASP.NET control that is used to provide advertisements to Web pages.
The AdRotatorcontrol associates with one or many advertisements, which randomly displays one by one
at a time when the Web page is refreshed. The AdRotator control advertisements are associated with
links; therefore, when you click on an advertisement, it redirects you to other pages.

The AdRotator control is associated with a data source, which is normally an xml file or a database
table. A data source contains all the information, such as advertisement graphics reference, link, and
alternate text. Therefore, when you use the AdRotator control, you should first create a data source
and then associate it with the AdRotator control.

What do you understand by the culture?

The culture denotes a combination of a language and optionally a region or a country. The contents of a
Web page of a multilingual Web site are changed according to the culture defined in the operating system
of the user accessing the Web page.

What is the code-behind feature in ASP.NET?

The code-behind feature of ASP.NET enables you to divide an ASP.NET page into two files - one consisting
of the presentation data, and the second, which is also called the code-behind file, consisting of all the
business logic. The presentation data contains the interface elements, such as HTML controls and Web
server controls, and the code-behind contains the event-handling process to handle the events that are
fired by these controls. The file that contains the presentation data has the .aspx extension. The code
behind file has either the .cs extension (if you are using the programming language C#) or the .vb (if
you are using the programming language Visual Basic .NET) extension.

Explain the validation controls. How many validation controls in ASP.NET 4.0?
Validation controls are responsible to validate the data of an input control. Whenever you provide any
input to an application, it performs the validation and displays an error message to user, in case the
validation fails.

ASP.NET 4.0 contains the following six types of validation controls:

• CompareValidator - Performs a comparison between the values contained in two controls.


• CustomValidator - Writes your own method to perform extra validation.
• RangeValidator- Checks value according to the range of value.
• RegularExpressionValidator - Ensures that input is according to the specified pattern or
not.
• RequiredFieldValidator - Checks either a control is empty or not.
• ValidationSummary - Displays a summary of all validation error in a central location.
What is difference between a Label control and a Literal control?

The Label control's final html code has an HTML tag; whereas, the Literal control's final html code
contains only text, which is not surrounded by any HTML tag.

How many types of Cookies are available in ASP.NET?

There are two types of Cookies available in ASP.NET:

• Session Cookie - Resides on the client machine for a single session until the user does not log
out.
• Persistent Cookie - Resides on a user's machine for a period specified for its expiry, such as 10
days, one month, and never.

The user can set this period manually.

What is the use of the Global.asax file?

The Global.asax file executes application-level events and sets application-level variables.

What are the Culture and UICulture values?

The Culture value determines the functions, such as Date and Currency, which are used to format data
and numbers in a Web page. The UICulture value determines the resources, such as strings or images,
which are loaded for a Web page in a Web application.

What is the use of the <sessionState> tag in the web.config file?

The <sessionState> tag is used to configure the session state features. To change the default timeout,
which is 20 minutes, you have to add the following code snippet to the web.config file of an
application:<sessionState timeout="40"/>

Which method do you use to kill explicitly a users session?


The Session.Abandon() method kills the user session explicitly.

Which class is inherited when an ASP.NET server control is added to a Web form?

The System.Web.UI.WebControls class is inherited when an ASP.NET server control is added to a Web
form.

What events are fired when a page loads?

The following events fire when a page loads:

• Init() - Fires when the page is initializing.


• LoadViewState() - Fires when the view state is loading.
• LoadPostData() - Fires when the postback data is processing.
• Load() - Fires when the page is loading.
• PreRender() - Fires at the brief moment before the page is displayed to the user as HTML.
• Unload() - Fires when the page is destroying the instances of server controls.
What are navigation controls? How many navigation controls are there in ASP.NET 4.0?

Navigation controls help you to navigate in a Web application easily. These controls store all the links in a
hierarchical or drop-down structure; thereby facilitating easy navigation in a Web application.

There are three navigation controls in ASP.Net 4.0.

• SiteMapPath
• Menu
• TreeView
What is cross-page posting in ASP.NET?
The Server.Transfer() method is used to post data from one page to another. In this case, the URL
remains the same. However, in cross page posting, data is collected from different Web pages and is
displayed on a single page. To do so, you need to set the PostBackUrl property of the control, which
specifies the target page. In the target page, you can access the PreviousPage property. For this, you
need to use the@PreviousPageType directive. You can access the controls of previous page by using
the FindControl()method.

Explain the Application and Session objects in ASP.NET.

Application state is used to store data corresponding to all the variables of an ASP.NET Web application.
The data in an application state is stored once and read several times. Application state uses
theHttpApplicationState class to store and share the data throughout the application. You can
access the information stored in an application state by using the HttpApplication class property.
Data stored in the application state is accessible to all the pages of the application and is the same for all
the users accessing the application. The HttpApplicationState class provides a lock method, which
you can use to ensure that only one user is able to access and modify the data of an application at any
instant of time.

Each client accessing a Web application maintains a distinct session with the Web server, and there is also
some specific information associated with each of these sessions. Session state is defined in
the<sessionState> element of the web.config file. It also stores the data specific to a user session in
session variables. Different session variables are created for each user session. In addition, session
variables can be accessed from any page of the application. When a user accesses a page, a session ID
for the user is created. The session ID is transferred between the server and the client over the HTTP
protocol using cookies.

What are Web server controls in ASP.NET?

The ASP.NET Web server controls are objects on the ASP.NET pages that run when the Web page is
requested. Many Web server controls, such as button and text box, are similar to the HTML controls. In
addition to the HTML controls, there are many controls, which include complex behavior, such as the
controls used to connect to data sources and display data.

What are the various ways of authentication techniques in ASP.NET?

There are various techniques in ASP.NET to authenticate a user. You can use one of the following ways of
authentication to select a built-in authentication provider:

• Windows Authentication - This mode works as the default authentication technique. It can
work with any form of Microsoft Internet Information Services (IIS) authentication, such as Basic,
Integrated Windows authentication (NTLM/Kerberos), Digest, and certificates. The syntax of
Windows authentication mode is given as follows: <authentication mode="windows" />
• Forms Authentication - You can specify this mode as a default authentication mode by using
the following code snippet: <authentication mode="Forms"/>
• Passport - This mode works with Microsoft Passport authentication, as shown in the following
code snippet: <authentication mode = "Passport"/>

What is the use of web.config? What is the difference between machine.config and
web.config?

ASP.NET configuration files are XML-based text files for application-level settings and are saved with the
name web.config. These files are present in multiple directories on an ASP.NET Web application server.
Theweb.config file sets the configuration settings to the directory it is placed in and to all the virtual
sub folders under it. The settings in sub directories can optionally override or change the settings
specified in the base directory.

The difference between the web.config and machine.config files is given as follows:

• <WinDir>\Microsoft.NET\Framework\<version>\config\machine.config provides
default configuration settings for the entire machine. ASP.NET configures IIS to prohibit the
browser directly from accessing the web.config files to make sure that their values cannot be
public. Attempts to access those files cause ASP.NET to return the 403: Access Forbidden error.
• ASP.NET uses these web.config configuration files at runtime to compute hierarchically a sole
collection of settings for every URL target request. These settings compute only once and cached
across further requests. ASP.NET automatically checks for changing file settings and do not
validate the cache if any of the configuration changes made.

Explain the concept of states in ASP.NET.

State is quite an innovative concept in Web development because it eliminates the drawback of losing
state data due to reloading of a Web page. By using states in a Web application, you can preserve the
state of the application either at the server or client end. The state of a Web application helps you to
store the runtime changes that have been made to the Web application. For example, as already
described earlier, a change in the data source of the Web application might be initiated by a user when
he/she selects and saves some products in the shopping cart.

If you are not using states, these changes are discarded and are not saved. You may think that the whole
concept of storing states is optional. However, under certain circumstances, using states with applications
is imperative. For example, it is necessary to store states for Web applications, such as an e-commerce
shopping site or an Intranet site of a company, to keep track of the requests of the users for the items
they have selected on the shopping site or the days requested for vacation on the Intranet site.

Can we validate a DropDownList by RequiredFieldValidator?

Yes, we can validate a DropDownList by RequiredFieldValidator. To perform this validation, we have


to set the InitialValue property of RequiredFieldValidator control.

What are Session state modes in ASP.NET?


ASP.NET supports different session state storage options:
•In-Process is the default approach. It stores session state locally on same web server memory where
the application is running.
•StateServer mode stores session state in a process other than the one where application is running.
Naturally, it has added advantages that session state is accessible from multiple web servers in a Web
Farm and also session state will remain preserved even web application is restarted.
•SQLServer mode stores session state in SQL Server database. It has the same advantages as that of
StateServer.
•Custom modes allows to define our custom storage provider.
•Off mode disables session storage.

MVC
1. Explain MVC (Model-View-Controller) in general?
MVC (Model-View-Controller) is an architectural software pattern that basically decouples various components of a
web application. By using MVC pattern, we can develop applications that are more flexible to changes without
affecting the other components of our application.
• "Model", is basically domain data.
• "View", is user interface to render domain data.
• "Controller", translates user actions into appropriate operations performed on model.
2. What is ASP.NET MVC?
ASP.NET MVC is a web development framework from Microsoft that is based on MVC (Model-View-Controller)
architectural design pattern. Microsoft has streamlined the development of MVC based applications using ASP.NET
MVC framework.

3. Difference between ASP.NET MVC and ASP.NET WebForms?


ASP.NET Web Forms uses Page controller pattern approach for rendering layout, whereas ASP.NET MVC uses Front
controller approach. In case of Page controller approach, every page has its own controller i.e. code-behind file that
processes the request. On the other hand, in ASP.NET MVC, a common controller for all pages processes the requests.

Follow the link for the difference between the ASP.NET MVC and ASP.NET WebForms.
4. What are the Core features of ASP.NET MVC?
Core features of ASP.NET MVC framework are:
• Clear separation of application concerns (Presentation and Business Logic)
• An extensible and pluggable framework
• Extensive support for ASP.NET Routing
• Support for existing ASP.NET features

Follow for detailed understanding of above mentioned core features.

5. Can you please explain the request flow in ASP.NET MVC framework?
Request flow for ASP.NET MVC framework is as follows:

Request hits the controller coming from client. Controller plays its role and decides which model to use in
order to serve the request. Further passing that model to view which then transforms the model and generate
an appropriate response that is rendered to client.
6. What is Routing in ASP.NET MVC?
In case of a typical ASP.NET application, incoming requests are mapped to physical files such as .aspx file.
ASP.NET MVC framework uses friendly URLs that more easily describe user’s action but not mapped to
physical files.

ASP.NET MVC framework uses a routing engine, that maps URLs to controller classes. We can define
routing rules for the engine, so that it can map incoming request URLs to appropriate controller.
Practically, when a user types a URL in a browser window for an ASP.NET MVC application and presses “go”
button, routing engine uses routing rules that are defined in Global.asax file in order to parse the URL and
find out the path of corresponding controller.

7. What is the difference between ViewData, ViewBag and TempData?


In order to pass data from controller to view and in next subsequent request, ASP.NET MVC framework
provides different options i.e. ViewData, ViewBag and TempData.

Both ViewBag and ViewData are used to to communicate between controller and corresponding view.But
this communication is only for server call, it becomes null if redirect occurs. So, in short, its a mechanism to
maintain state between controller and corresponding view.
ViewData is a dictionary object while ViewBag is a dynamic property (a new C# 4.0 feature). viewData being
a dictionary object is accessible using strings as keys and also requires typecasting for complex types.On
the other hand, ViewBag doesn't have typecasting and null checks.

TempData is also a dictionary object that stays for the time of an HTTP Request. So, Tempdata can be used
to maintain data between redirects i.e from one controller to the other controller.

8. What are Action Methods in ASP.NET MVC?

As I already explained about request flow in ASP.NET MVC framework that request coming from client hits
controller first. Actually MVC application determines the corresponding controller by using routing rules
defined in Global.asax. And controllers have specific methods for each user actions. Each request coming to
controller is for a specific Action Method. The following code example, “ShowBooks” is an example of an
Action Method.

public ViewResult ShowBooks(int id)


{
var computerBook = db.Books.Where(p => P.BookID == id).First();
return View(computerBook);
}

9.Explain the role of Model in ASP.NET MVC?


One of the core feature of ASP.NET MVC is that it separates the input and UI logic from business logic. Role
of Model in ASP.NET MVC is to contain all application logic including validation, business and data access
logic except view i.e. input and controller i.e UI logic.

Model is normally responsible for accessing data from some persistent medium like database and
manipulate it.

10.What are Action Filters in ASP.NET MVC?


If we need to apply some specific logic before or after action methods, we use action filters. We can apply
these action filters to a controller or a specific controller action. Action filters are basically custom classes that
provide a mean for adding pre-action or post-action behavior to controller actions.
For example,

• Authorize filter can be used to restrict access to a specific user or a role.


• OutputCache filter can cache the output of a controller action for a specific duration.

What are routing in MVC?


Routing helps you to define a URL structure and map the URL with the controller.
For instance let’s say we want that when any user types “http://localhost/View/ViewCustomer/” , it
goes
to the “Customer” Controller and invokes “DisplayCustomer” action. This is defined by adding an
entry
in to the “routes” collection using the “maproute” function. Below is the under lined code which
shows
how the URL structure and mapping with controller and action is defined.

routes.MapRoute(
"View", // Route name
"View/ViewCustomer/{id}", // URL with parameters
new { controller = "Customer", action = "DisplayCustomer", id
= UrlParameter.Optional }); // Parameter defaults

Where is the route mapping code written?


The route mapping code is written in the “global.asax” file.

Can we map multiple URL’s to the same action?


Yes , you can , you just need to make two entries with different key names and specify the same
controller and action.

How can we navigate from one view to other view using hyperlink?
By using “ActionLink” method as shown in the below code. The below code will create a simple
URL
which help to navigate to the “Home” controller and invoke the “GotoHome” action.
<%= Html.ActionLink("Home","Gotohome") %>

How can we restrict MVC actions to be invoked only by GET or POST?


We can decorate the MVC action by “HttpGet” or “HttpPost” attribute to restrict the type of HTTP
calls.
For instance you can see in the below code snippet the “DisplayCustomer” action can only be
invoked by

“HttpGet”. If we try to make Http post on “DisplayCustomer” it will throw an error.


[HttpGet]
public ViewResult DisplayCustomer(int id)
{
Customer objCustomer = Customers[id];
return View("DisplayCustomer",objCustomer);
}

How can we maintain session in MVC?


Sessions can be maintained in MVC by 3 ways tempdata ,viewdata and viewbag.

Temp data: -Helps to maintain data when you move from one controller to other controller or from one
action to other action. In other words when you redirect,“tempdata” helps to maintain data between those
redirects. It internally uses session variables.

View data: - Helps to maintain data when you move from controller to view.

View Bag: - It’s a dynamic wrapper around view data. When you use “Viewbag” type casting is not
required. It uses the dynamic keyword internally.

Session variables: - By using session variables we can maintain data from any entity to any entity.

Hidden fields and HTML controls: - Helps to maintain data from UI to controller only. So you can send
data from HTML controls or hidden fields to the controller using POST or GET HTTP methods.

Partial view
Partial view is a reusable view (like a user control) which can be embedded inside other view.
For example let’s say all your pages of your site have a standard structure with left menu, header
and footer.

How can we do validations in MVC?


One of the easy ways of doing validation in MVC is by using data annotations. Data annotations are
nothing but attributes which you can be applied on the model properties. For example in the below
code
snippet we have a simple “customer” class with a property “customercode”.
This”CustomerCode” property is tagged with a “Required” data annotation attribute. In other words
if this
model is not provided customer code it will not accept the same.

public class Customer


{
[Required(ErrorMessage="Customer code is required")]
public string CustomerCode
{
set;
get;
}
}

What is razor inMVC?


It’s a light weight view engine. Till MVC we had only one view type i.e.ASPX, Razor was
introduced in
MVC 3.
Why razor when we already had ASPX?
Razor is clean, lightweight and syntaxes are easy as compared to ASPX. For example in ASPX to
display
simple time we need to write.
<%=DateTime.Now%>
In Razor it’s just one line of code.
@DateTime.Now
So which is a better fit Razor or ASPX?
As per Microsoft razor is more preferred because it’s light weight and has simple syntaxes. But my
suggestion would be to answer more realtime….

What is the difference between “ActionResult” and “ViewResult”?


“ActionResult” is an abstract class while “ViewResult” derives from “ActionResult” class.
“ActionResult” has several derived classes like “ViewResult” ,”JsonResult” , “FileStreamResult”
and so
on.
“ActionResult” can be used to exploit polymorphism and dynamism. So if you are returning
different
types of view dynamically “ActionResult” is the best thing. For example in the below code snippet
you
can see we have a simple action called as “DynamicView”. Depending on the flag (“IsHtmlView”)
it will
either return “ViewResult” or “JsonResult”.
public ActionResult DynamicView()
{
if (IsHtmlView)
return View(); // returns simple ViewResult
else
return Json(); // returns JsonResult view
}
What are the different types of results in MVC?

There 12 kinds of results in MVC, at the top is “ActionResult”class which is a base class that
canhave11subtypes’sas listed below: -

1. ViewResult - Renders a specified view to the response stream


2. PartialViewResult - Renders a specified partial view to the response stream
3. EmptyResult - An empty response is returned
4. RedirectResult - Performs an HTTP redirection to a specified URL
5. RedirectToRouteResult - Performs an HTTP redirection to a URL that is determined by the
routing engine, based on given route data
6. JsonResult - Serializes a given ViewData object to JSON format
7. JavaScriptResult - Returns a piece of JavaScript code that can be executed on the client
8. ContentResult - Writes content to the response stream without requiring a view
9. FileContentResult - Returns a file to the client
10. FileStreamResult - Returns a file to the client, which is provided by a Stream
11. FilePathResult - Returns a file to the client

What are the benefits of using MVC?


There are two big benefits of MVC:
•Separation of concerns is achieved as we are moving the code-behind to a separate class file. By
moving the binding code to a separate class file we can reuse the code to a great extent.
•Automated UI testing is possible because now the behind code (UI interaction code) has moved to a
simple .NET class. This gives us opportunity to write unit tests and automate manual testing.

What is the difference between each version of MVC?


Below is a detailed table of differences. But during an interview it’s difficult to talk about all of
them due to time limitation. So I have highlighted the important differences that you can run
through before the interviewer.
MVC 2 MVC 3 MVC 4
• Client-side validation • Razor • ASP.NET Web API
• Templated Helpers Areas • Readymade project • Refreshed and modernized
• Asynchronous Controllers templates default project templates.
• Html.ValidationSummary Helper Method• HTML 5 enabled New mobile project
• DefaultValueAttribute in Action-Method templates template.
• Parameters binding • Support for Multiple • Many new features to
• Binary data with Model Binders View Engines, support mobile apps
• DataAnnotations Attributes JavaScript, and AJAX • Enhanced support for
• Model-Validator Providers • Model Validation asynchronous methods
• New RequireHttpsAttributeAction Filter Improvements
• Templated Helpers
• Display Model-Level Errors

What is the difference between “HTML.TextBox” vs “HTML.TextBoxFor”?


Both of them provide the same HTML output, “HTML.TextBoxFor” is strongly typed while
“HTML.TextBox” isn’t. Below is a simple HTML code which just creates a simple textbox with
“CustomerCode” as name.
Html.TextBox("CustomerCode")
Below is “Html.TextBoxFor” code which creates HTML textbox using the property name ‘CustomerCode”
from object “m”.

Html.TextBoxFor(m => m.CustomerCode)

In the same way we have for other HTML controls like for checkbox we have “Html.CheckBox” and
“Html.CheckBoxFor”.

What is routing in MVC?


Routing helps you to define a URL structure and map the URL with the controller.
For instance let’s say we want that when a user types “http://localhost/View/ViewCustomer/”, it goes to
the “Customer” Controller and invokes the DisplayCustomer action. This is defined by adding an
entry in to the routescollection using the maproute function. Below is the underlined code which
shows how the URL structure and mapping with controller and action is defined.
Collapse | Copy Code

routes.MapRoute(
"View", // Route name
"View/ViewCustomer/{id}", // URL with parameters
new { controller = "Customer", action = "DisplayCustomer",
id = UrlParameter.Optional }); // Parameter defaults

Where is the route mapping code written?


The route mapping code is written in the “global.asax” file.

Can we map multiple URL’s to the same action?


Yes, you can, you just need to make two entries with different key names and specify the same
controller and action.

How can we navigate from one view to another using a hyperlink?


By using the ActionLink method as shown in the below code. The below code will create a simple
URL which helps to navigate to the “Home” controller and invoke the GotoHome action.

<%= Html.ActionLink("Home","Gotohome") %>

How can we restrict MVC actions to be invoked only by GET or POST?


We can decorate the MVC action with the HttpGet or HttpPost attribute to restrict the type of HTTP
calls. For instance you can see in the below code snippet the DisplayCustomer action can only be
invoked by HttpGet. If we try to make HTTP POST on DisplayCustomer, it will throw an error.

[HttpGet]
public ViewResult DisplayCustomer(int id)
{
Customer objCustomer = Customers[id];
return View("DisplayCustomer",objCustomer);
}

How can we maintain sessions in MVC?


Sessions can be maintained in MVC by three ways: tempdata, viewdata, and viewbag.

Temp data - Helps to maintain data when you move from one controller to another controller or from
one action to another action. In other words when you redirect, tempdata helps to maintain data
between those redirects. It internally uses session variables.

What is the difference between tempdata, viewdata, and viewbag?


•View data - Helps to maintain data when you move from controller to view.
•View Bag - It’s a dynamic wrapper around view data. When you use Viewbag type, casting is not
required. It uses the dynamic keyword internally.
•Session variables - By using session variables we can maintain data from any entity to any entity.
•Hidden fields and HTML controls - Helps to maintain data from UI to controller only. So you can send
data from HTML controls or hidden fields to the controller using POST or GET HTTP methods.

What are the new features of MVC3?


ASP.NET MVC 3 shipped just 10 months after MVC 2 in Jan 2011. Some of the top features in
MVC 3 included:
•The Razor view engine
•Support for .NET 4 Data Annotations
•Improved model validation
•Greater control and flexibility with support for dependency resolution and global action filters
•Better JavaScript support with unobtrusive JavaScript, jQuery Validation, and JSON binding
•Use of NuGet to deliver software and manage dependencies throughout the platform

What are the new features of MVC4?


Following are the top features of MVC4:
•ASP.NET Web API
•Enhancements to default project templates
•Mobile project template using jQuery Mobile
•Display Modes
•Task support for Asynchronous Controllers
•Bundling and minification

Explain “page lifecycle” of an ASP.NET MVC?


Following processes are performed by ASP.NET MVC page:
1.App initialization
2.Routing
3.Instantiate and execute controller
4.Locate and invoke controller action
5.Instantiate and render view
Advantages of MVC Framework?
1.Provides a clean separation of concerns between UI (Presentation layer), model (Transfer
objects/Domain Objects/Entities) and Business Logic (Controller)
2.Easy to UNIT Test
3.Improved reusability of views/model. One can have multiple views which can point to the same
model and vice versa
4.Improved structuring of the code

What do you mean by Separation of Concerns?


As per Wikipedia, 'the process of breaking a computer program into distinct features that overlap in
functionality as little as possible'. MVC design pattern aims to separate content from presentation
and data-processing from content.

Where do we see Separation of Concerns in MVC?


Between the data-processing (Model) and the rest of the application.
When we talk about Views and Controllers, their ownership itself explains separation. The views
are just the presentation form of an application, it does not have to know specifically about the
requests coming from controller. The Model is independent of View and Controllers, it only holds
business entities that can be passed to any View by the controller as required for exposing them to
the end user. The controller is independent of Views and Models, its sole purpose is to handle
requests and pass it on as per the routes defined and as per the need of rendering views. Thus our
business entities (model), business logic (controllers) and presentation logic (views) lie in
logical/physical layers independent of each other.

What is Razor View Engine?


Razor is the first major update to render HTML in MVC3. Razor was designed specifically as a
view engine syntax. It has one main focus: code-focused templating for HTML generation. Here’s
how that same markup would be generated using Razor:

What is Unobtrusive JavaScript?


Unobtrusive JavaScript is a general term that conveys a general philosophy, similar to the term
REST (Representational State Transfer). The high-level description is that unobtrusive JavaScript
doesn’t intermix JavaScript code in your page markup. For example, rather than hooking in via
event attributes like onclick and onsubmit, the unobtrusive JavaScript attaches to elements by their
ID or class, often based on the presence of other attributes (such as HTML5 data- attributes).
It’s got semantic meaning, and all of it — the tag structure, element attributes, and so on — should
have a precise meaning. Strewing JavaScript gunk across the page to facilitate interaction (I’m
looking at you, __doPostBack!) harms the content of the document.

What is JSON Binding?


MVC 3 included JavaScript Object Notation (JSON) binding support via the
new JsonValueProviderFactory, enabling the action methods to accept and model-bind data in
JSON format. This is especially useful in advanced Ajax scenarios like client templates and data
binding that need to post data back to the server.
What is Dependency Resolution?
MVC 3 introduced a new concept called a dependency resolver, which greatly simplified the use of
dependency injection in your applications. This made it easier to decouple application components,
making them more configurable and easier to test.
Support was added for the following scenarios:
•Controllers (registering and injecting controller factories, injecting controllers)
•Views (registering and injecting view engines, injecting dependencies into view pages)
•Action filters (locating and injecting filters)
•Model binders (registering and injecting)
•Model validation providers (registering and injecting)
•Model metadata providers (registering and injecting)
•Value providers (registering and injecting)

What are Display Modes in MVC4?


Display modes use a convention-based approach to allow selecting different views based on the
browser making the request. The default view engine first looks for views with names ending
with .Mobile.cshtml when the browser’s user agent indicates a known mobile device. For example,
if we have a generic view titled Index.cshtml and a mobile view titled Index.Mobile.cshtml, MVC 4
will automatically use the mobile view when viewed in a mobile browser.
Additionally, we can register your own custom device modes that will be based on your own
custom criteria — all in just one code statement. For example, to register a WinPhone device mode
that would serve views ending with.WinPhone.cshtml to Windows Phone devices, you’d use the
following code in the Application_Start method of your Global.asax:

What are the differences between ViewData and ViewBag? (taken from a blog)
•ViewData is a dictionary of objects that is derived from ViewDataDictionary class and accessible
usingstrings as keys.
•ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
•ViewData requires typecasting for complex data type and checks for null values to avoid error.
•ViewBag doesn’t require typecasting for complex data type.
NOTE: Although there might not be a technical advantage to choosing one format over the other,
there are some critical differences to be aware of between the two syntaxes.
One obvious difference is that ViewBag works only when the key being accessed is a valid C#
identifier. For example, if you place a value in ViewData["KeyWith Spaces"], you can’t access that
value using ViewBag because the codewon’t compile.
Another key issue to be aware of is that dynamic values cannot be passed in as parameters to
extension methods. The C# compiler must know the real type of every parameter at compile time in
order for it to choose the correct extension method.
If any parameter is dynamic, compilation will fail. For example, this code will always
fail: @Html.TextBox("name", ViewBag.Name). To work around this, either
use ViewData["Name"] or cast the value to a specific type: (string) ViewBag.Name.

What is TempData?
TempData is a dictionary derived from the TempDataDictionary class and stored in short lives
session. It is astring key and object value.
It keeps the information for the time of an HTTP Request. This means only from one page to
another. It helps to maintain data when we move from one controller to another controller or from
one action to other action. In other words, when we redirect Tempdata helps to maintain data
between those redirects. It internally uses session variables. Temp data use during the current and
subsequent request only means it is used when we are sure that the next request will be redirecting
to next view. It requires typecasting for complex data type and checks for null values to avoid error.
Generally it is used to store only one time messages like error messages, validation messages.

Explain Routing in MVC?


A route is a URL pattern that is mapped to a handler. The handler can be a physical file, such as
an .aspx file in a Web Forms application. Routing module is responsible for mapping incoming browser
requests to particular MVC controller actions.
Routing within the ASP.NET MVC framework serves two main purposes:
•It matches incoming requests that would not otherwise match a file on the file system and maps the
requests to a controller action.
•It constructs outgoing URLs that correspond to controller actions.

What are Layouts in ASP.NET MVC Razor?


Layouts in Razor help maintain a consistent look and feel across multiple views within our
application. As compared to Web Forms, layouts serve the same purpose as master pages, but offer
both a simpler syntax and greater flexibility.

We can use a layout to define a common template for your site (or just part of it). This template
contains one or more placeholders that the other views in your application provide content for. In
some ways, it’s like an abstract base class for your views.
E.g. declared at the top of view as:

@{
Layout = "~/Views/Shared/SiteLayout.cshtml";
}

What is ViewStart?
For group of views that all use the same layout, this can get a bit redundant and harder to maintain.
The _ViewStart.cshtml page can be used to remove this redundancy. The code within this file is
executed before the code in any view placed in the same directory. This file is also recursively
applied to any view within a subdirectory.

When we create a default ASP.NET MVC project, we find there is already a _ViewStart .cshtml file
in the Viewsdirectory. It specifies a default layout:

@{
Layout = "~/Views/Shared/_Layout.cshtml";
}

Because this code runs before any view, a view can override the Layout property and choose a
different one. If a set of views shares common settings, the _ViewStart.cshtml file is a useful place
to consolidate these common view settings. If any view needs to override any of the common
settings, the view can set those values to another value.
Note: Some of the content has been taken from various books/articles.

What are HTML Helpers?


HTML helpers are methods we can invoke on the HTML property of a view. We also have access to
URL helpers (via the Url property), and AJAX helpers (via the Ajax property). All these helpers
have the same goal: to make views easy to author. The URL helper is also available from within the
controller. Most of the helpers, particularly the HTML helpers, output HTML markup. For example,
the BeginForm helper is a helper we can use to build a robust form tag for our search form, but
without using lines and lines of code:

@using (Html.BeginForm("Search", "Home", FormMethod.Get)) {


<input type="text" name="q" />
<input type="submit" value="Search" />
}

What is Html.ValidationSummary?
The ValidationSummary helper displays an unordered list of all validation errors in
the ModelState dictionary. The Boolean parameter you are using (with a value of true) is telling the
helper to exclude property-level errors. In other words, you are telling the summary to display only
the errors in ModelState associated with the model itself, and exclude any errors associated with a
specific model property. We will be displaying property-level errors separately. Assume you have
the following code somewhere in the controller action rendering the edit view:

ModelState.AddModelError("", "This is all wrong!");


ModelState.AddModelError("Title", "What a terrible name!");
The first error is a model-level error, because you didn’t provide a key (or provided an empty key)
to associate the error with a specific property. The second error you associated with
the Title property, so in your view it will not display in the validation summary area (unless you
remove the parameter to the helper method, or change the value to false). In this scenario, the helper
renders the following HTML:

<div class="validation-summary-errors">
<ul>
<li>This is all wrong!</li>
</ul>
</div>

Other overloads of the ValidationSummary helper enable you to provide header text and set specific
HTML attributes.
NOTE: By convention, the ValidationSummary helper renders the CSS class validation-summary-
errors along with any specific CSS classes you provide. The default MVC project template includes
some styling to display these items in red, which you can change in styles.css.

What are Validation Annotations?


Data annotations are attributes you can find
in System.ComponentModel.DataAnnotations namespace. These attributes provide server-side
validation, and the framework also supports client-side validation when you use one of the
attributes on a model property. You can use four attributes in the DataAnnotations namespace to
cover common validation scenarios,
Required, String Length, Regular Expression, Range.

What is Html.Partial?
The Partial helper renders a partial view into a string. Typically, a partial view contains reusable
markup you want to render from inside multiple different views. Partial has four overloads:

public void Partial(string partialViewName);


public void Partial(string partialViewName, object model);
public void Partial(string partialViewName, ViewDataDictionary viewData);
public void Partial(string partialViewName, object model,
ViewDataDictionary viewData);

What is Html.RenderPartial?
The RenderPartial helper is similar to Partial, but RenderPartial writes directly to the response
output stream instead of returning a string. For this reason, you must place RenderPartial inside a
code block instead of a code expression. To illustrate, the following two lines of code render the
same output to the output stream:

@{Html.RenderPartial("AlbumDisplay "); }
@Html.Partial("AlbumDisplay ")

If they are the same, then which one to use?


In general, you should prefer Partial to RenderPartial because Partial is more convenient (you don’t
have to wrap the call in a code block with curly braces). However, RenderPartial may result in
better performance because it writes directly to the response stream, although it would require a lot
of use (either high site traffic or repeated calls in a loop) before the difference would be noticeable.

How do you return a partial view from controller?

return PartialView(options); //options could be Model or View name


What are different ways of returning a View?
There are different ways for returning/rendering a view in MVC Razor. E.g. return View(),
returnRedirectToAction(), return Redirect() and return RedirectToRoute().

SQL Server

Inner Join
Inner join is the most common type of Join which is used to combine the rows from two tables and
create a result set containing only such records that are present in both the tables based on the
joining condition (predicate).

Inner join returns rows when there is at least one match in both tables

If none of the record matches between two tables, then INNER JOIN will return a NULL set. Below
is an example of INNER JOIN and the resulting set.

SELECT dept.name DEPARTMENT, emp.name EMPLOYEE

FROM DEPT dept, EMPLOYEE emp

WHERE emp.dept_id = dept.id

Outer Join
Outer Join, on the other hand, will
return matching rows from both tables
Outer Join can be full outer or single
as well as any unmatched rows from
outer
one or both the tables (based on
whether it is single outer or full outer
join respectively).

Notice in our record set that there is no employee in the department 5 (Logistics). Because of this if
we perform inner join, then Department 5 does not appear in the above result. However in the
below query we perform an outer join (dept left outer join emp), and we can see this department.

SELECT dept.name DEPARTMENT, emp.name EMPLOYEE

FROM DEPT dept, EMPLOYEE emp

WHERE dept.id = emp.dept_id (+)

What is the difference between JOIN and UNION?


SQL JOIN allows us to “lookup” records on other table based on the given conditions between two tables. For
example, if we have the department ID of each employee, then we can use this department ID of the
employee table to join with the department ID of department table to lookup department names.

UNION operation allows us to add 2 similar data sets to create resulting data set that contains all the data
from the source data sets. Union does not require any condition for joining. For example, if you have 2
employee tables with same structure, you can UNION them to create one result set that will contain all the
employees from both of the tables.

SELECT * FROM EMP1

UNION

SELECT * FROM EMP2;

What is the difference between UNION and UNION ALL?


UNION and UNION ALL both unify for add two structurally similar data sets, but UNION operation returns only
the unique records from the resulting data set whereas UNION ALL will return all the rows, even if one or
more rows are duplicated to each other.

In the following example, I am choosing exactly the same employee from the emp table and performing
UNION and UNION ALL. Check the difference in the result.

SELECT * FROM EMPLOYEE WHERE ID = 5

UNION ALL

SELECT * FROM EMPLOYEE WHERE ID = 5

SELECT * FROM EMPLOYEE WHERE ID = 5

UNION
SELECT * FROM EMPLOYEE WHERE ID = 5

What is the difference between WHERE clause and HAVING clause?


WHERE and HAVING both filters out records based on one or more conditions. The difference is, WHERE
clause can only be applied on a static non-aggregated column whereas we will need to use HAVING for
aggregated columns.

To understand this, consider this example.


Suppose we want to see only those departments where department ID is greater than 3. There is no
aggregation operation and the condition needs to be applied on a static field. We will use WHERE clause here:

SELECT * FROM DEPT WHERE ID > 3

We will need to use HAVING clause here:

SELECT dept.name DEPARTMENT, avg(emp.sal) AVG_SAL

FROM DEPT dept, EMPLOYEE emp

WHERE dept.id = emp.dept_id (+)

GROUP BY dept.name

HAVING AVG(emp.sal) > 80

What is the difference among UNION, MINUS and INTERSECT?


UNION combines the results from 2 tables and eliminates duplicate records from the result set.

MINUS operator when used between 2 tables, gives us all the rows from the first table except the rows which
are present in the second table.

INTERSECT operator returns us only the matching or common rows between 2 result sets.

To understand these operators, let’s see some examples. We will use two different queries to extract data
from our emp table and then we will perform UNION, MINUS and INTERSECT operations on these two sets of
data.

UNION

SELECT * FROM EMPLOYEE WHERE ID = 5

UNION

SELECT * FROM EMPLOYEE WHERE ID = 6

MINUS

SELECT * FROM EMPLOYEE


MINUS

SELECT * FROM EMPLOYEE WHERE ID > 2

INTERSECT

SELECT * FROM EMPLOYEE WHERE ID IN (2, 3, 5)

INTERSECT

SELECT * FROM EMPLOYEE WHERE ID IN (1, 2, 4, 5)

What is Self Join and why is it required?


Self Join is the act of joining one table with itself.

Self Join is often very useful to convert a hierarchical structure into a flat
structure

In our employee table example above, we have kept the manager ID of each employee in the same row as that
of the employee. This is an example of how a hierarchy (in this case employee-manager hierarchy) is stored
in the RDBMS table. Now, suppose if we need to print out the names of the manager of each employee right
beside the employee, we can use self join. See the example below:

SELECT e.name EMPLOYEE, m.name MANAGER

FROM EMPLOYEE e, EMPLOYEE m

WHERE e.mgr_id = m.id (+)

The only reason we have performed a left outer join here (instead of INNER JOIN) is we have one employee in
this table without a manager (employee ID = 1). If we perform inner join, this employee will not show-up.

How can we transpose a table using SQL (changing rows to


column or vice-versa) ?

The usual way to do it in SQL is to use CASE statement or DECODE statement.

How to generate row number in SQL Without ROWNUM

Generating a row number – that is a running sequence of numbers for each row is not easy using plain SQL.
In fact, the method I am going to show below is not very generic either. This method only works if there is at
least one unique column in the table. This method will also work if there is no single unique column, but
collection of columns that is unique. Anyway, here is the query:

SELECT name, sal, (SELECT COUNT(*) FROM EMPLOYEE i WHERE o.name >= i.name) row_num

FROM EMPLOYEE o
order by row_num

What are the difference between clustered and a non-clustered index?

1. A clustered index is a special type of index that reorders the way records in the table are
physically stored. Therefore table can have only one clustered index. The leaf nodes of a clustered
index contain the data pages.
2. A non clustered index is a special type of index in which the logical order of the index does not
match the physical stored order of the rows on disk. The leaf node of a non clustered index does
not consist of the data pages. Instead, the leaf nodes contain index rows.

Clustered Index
The primary key created for the StudId column will create a clustered index for the Studid column.
A table can have only one clustered index on it.
When creating the clustered index, SQL server 2005 reads the Studid column and forms a Binary
tree on it. This binary tree information is then stored separately in the disc. Expand the
table Student and then expand theIndexes. You will see the following index created for you when
the primary key is created:
With the use of the binary tree, now the search for the student based on the studid decreases the
number of comparisons to a large amount. Let us assume that you had entered the following data in
the table student:
The index will form the below specified binary tree. Note that for a given parent, there are only one
or two Childs. The left side will always have a lesser value and the right side will always have a
greater value when compared to parent. The tree can be constructed in the reverse way also. That is,
left side higher and right side lower.
Now let us assume that we had written a query like below:

Select * from student where studid = 103;


Select * from student where studid = 107;
Execution without index will return value for the first query after third comparison.
Execution without index will return value for the second query at eights comparison.
Execution of first query with index will return value at first comparison.
Execution of second query with index will return the value at the third comparison. Look below:
1.Compare 107 vs 103 : Move to right node
2.Compare 107 vs 106 : Move to right node
3.Compare 107 vs 107 : Matched, return the record
If numbers of records are less, you cannot see a different one. Now apply this technique with a
Yahoo email user accounts stored in a table called say YahooLogin. Let us assume there are 33
million users around the world that have Yahoo email id and that is stored in the YahooLogin. When
a user logs in by giving the user name and password, the comparison required is 1 to 25, with the
binary tree that is clustered index.
Look at the above picture and guess yourself how fast you will reach into the level 25. Without
Clustered index, the comparison required is 1 to 33 millions.

The above explanation is for easy understanding. Now a days SQL server is using the B-Tree
techniques to represent the clustered index.
Got the usage of Clustered index? Let us move to Non-Clustered index.
Non Clustered Index
A non-clustered index is useful for columns that have some repeated values. Say for
example, AccountType column of a bank database may have 10 million rows. But, the distinct
values of account type may be 10-15. A clustered index is automatically created when we create the
primary key for the table. We need to take care of the creation of the non-clustered index.
Follow the steps below to create a Non-clustered index on our table Student based on the column
class.
1.After expanding the Student table, right click on the Indexes. And click on the New Index.
2.From the displayed dialog, type the index name as shown below and then click on the Add button
to select the column(s) that participate in the index. Make sure the Index type is Non-Clustered.
3.In the select column dialog, place a check mark for the column class. This tells that we need a
non-clustered index for the column Student.Class. You can also combine more than one column to
create the Index. Once the column is selected, click on the OK button. You will return the dialog
shown above with the selected column marked in blue. Our index has only one column. If you
selected more than one column, using theMoveUp and MoveDown button, you can change order of
the indexed columns. When you are using the combination of columns, always use the highly
repeated column first and more unique columns down in the list. For example, let use assume the
correct order for creating the Non-clustered index is: Class,DateOfBirth, PlaceOfBirth.

How Does a Non-Clustered Index Work?


A table can have more than one Non-Clustered index. But, it should have only one clustered index that
works based on the Binary tree concept. Non-Clustered column always depends on the Clustered
column on the database.
This can be easily explained with the concept of a book and its index page at the end. Let us assume
that you are going to a bookshop and found a big 1500 pages of C# book that says all about C#. When
you glanced at the book, it has all beautiful color pages and shiny papers. But, that is not only the
eligibility for a good book right? One you are impressed, you want to see your favorite topic of Regular
Expressions and how it is explained in the book. What will you do? I just peeped at you from behind and
recorded what you did as below:
1.You went to the Index page (it has total 25 pages). It is already sorted and hence you easily picked up
Regular Expression that comes on page Number 17.
2.Next, you noted down the number displayed next to it which is 407, 816, 1200-1220.
3.Your first target is Page 407. You opened a page in the middle, the page is greater than 500.
4.Then you moved to a somewhat lower page. But it still reads 310.
5.Then you moved to a higher page. You are very lucky you exactly got page 407. [Yes man you got it.
Otherwise I need to write more. OK?]
6.That’s all, you started exploring what is written about Regular expression on that page, keeping in
mind that you need to find page 816 also.
In the above scenario, the Index page is Non-Clustered index and the page numbers are clustered index
arranged in a binary tree. See how you came to the page 407 very quickly. Your mind actually traversed
the binary tree way left and right to reach the page 407 quickly.
Here, the class column with distinct values 1,2,3..12 will store the clustered index columns value along
with it. Say for example; Let us take only class value of 1. The Index goes like this:
e

1: 100, 104, 105

4.Click on the Index folder on the right side and you will see the non-clustered index based on the
column class is created for you.
What is OLTP (Online Transaction Processing)?

In OLTP - online transaction processing systems relational database design use the discipline of data
modeling and generally follow the Codd rules of data normalization in order to ensure absolute data
integrity. Using these rules complex information is broken down into its most simple structures (a table)
where all of the individual atomic level elements relate to each other and satisfy the normalization rules.
What's the difference between a primary key and a unique key?

Both primary key and unique key enforces uniqueness of the column on which they are defined. But by
default primary key creates a clustered index on the column, where are unique creates a nonclustered
index by default. Another major difference is that, primary key doesn't allow NULLs, but unique key
allows one NULL only.
What is difference between DELETE and TRUNCATE commands?

Delete command removes the rows from a table based on the condition that we provide with a WHERE
clause. Truncate will actually remove all the rows from a table and there will be no data in the table after
we run the truncate command.

1. TRUNCATE:
1. TRUNCATE is faster and uses fewer system and transaction log resources than DELETE.
2. TRUNCATE removes the data by deallocating the data pages used to store the table's
data, and only the page deallocations are recorded in the transaction log.
3. TRUNCATE removes all rows from a table, but the table structure, its columns,
constraints, indexes and so on, remains. The counter used by an identity for new rows is
reset to the seed for the column.
4. You cannot use TRUNCATE TABLE on a table referenced by a FOREIGN KEY constraint.
Because TRUNCATE TABLE is not logged, it cannot activate a trigger.
5. TRUNCATE cannot be rolled back.
6. TRUNCATE is DDL Command.
7. TRUNCATE Resets identity of the table
2. DELETE:
1. DELETE removes rows one at a time and records an entry in the transaction log for each
deleted row.
2. If you want to retain the identity counter, use DELETE instead. If you want to remove
table definition and its data, use the DROP TABLE statement.
3. DELETE Can be used with or without a WHERE clause
4. DELETE Activates Triggers.
5. DELETE can be rolled back.
6. DELETE is DML Command.
7. DELETE does not reset identity of the table.

Note: DELETE and TRUNCATE both can be rolled back when surrounded by TRANSACTION if the current
session is not closed. If TRUNCATE is written in Query Editor surrounded by TRANSACTION and if session
is closed, it can not be rolled back but DELETE can be rolled back.
When is the use of UPDATE_STATISTICS command?

This command is basically used when a large processing of data has occurred. If a large amount of
deletions any modification or Bulk Copy into the tables has occurred, it has to update the indexes to take
these changes into account. UPDATE_STATISTICS updates the indexes on these tables accordingly.
What are the properties and different Types of Sub-Queries?

1. Properties of Sub-Query
1. A sub-query must be enclosed in the parenthesis.
2. A sub-query must be put in the right hand of the comparison operator, and
3. A sub-query cannot contain an ORDER-BY clause.
4. A query can contain more than one sub-query.
2. Types of Sub-Query
1. Single-row sub-query, where the sub-query returns only one row.
2. Multiple-row sub-query, where the sub-query returns multiple rows,. and
3. Multiple column sub-query, where the sub-query returns multiple columns
What is SQL Profiler?

SQL Profiler is a graphical tool that allows system administrators to monitor events in an instance of
Microsoft SQL Server. You can capture and save data about each event to a file or SQL Server table to
analyze later. For example, you can monitor a production environment to see which stored procedures are
hampering performances by executing too slowly.

Use SQL Profiler to monitor only the events in which you are interested. If traces are becoming too large,
you can filter them based on the information you want, so that only a subset of the event data is
collected. Monitoring too many events adds overhead to the server and the monitoring process and can
cause the trace file or trace table to grow very large, especially when the monitoring process takes place
over a long period of time.
What is UNIQUE KEY constraint?

A UNIQUE constraint enforces the uniqueness of the values in a set of columns, so no duplicate values
are entered. The unique key constraints are used to enforce entity integrity as the primary key
constraints.
What is PRIMARY KEY?

A PRIMARY KEY constraint is a unique identifier for a row within a database table. Every table should
have a primary key constraint to uniquely identify each row and only one primary key constraint can be
created for each table. The primary key constraints are used to enforce entity integrity.
What is FOREIGN KEY?

A FOREIGN KEY constraint prevents any actions that would destroy links between tables with the
corresponding data values. A foreign key in one table points to a primary key in another table. Foreign
keys prevent actions that would leave rows with foreign key values when there are no primary keys with
that value. The foreign key constraints are used to enforce referential integrity.

What is CHECK Constraint?

A CHECK constraint is used to limit the values that can be placed in a column. The check constraints are
used to enforce domain integrity.
How to get @@ERROR and @@ROWCOUNT at the same time?

If @@Rowcount is checked after Error checking statement then it will have 0 as the value of
@@Recordcount as it would have been reset. And if @@Recordcount is checked before the error-checking
statement then @@Error would get reset. To get @@error and @@rowcount at the same time do both in
same statement and store them in local variable.
SELECT @RC = @@ROWCOUNT, @ER = @@ERROR

What is a Scheduled Jobs or What is a Scheduled Tasks?

Scheduled tasks let user automate processes that run on regular or predictable cycles. User can schedule
administrative tasks, such as cube processing, to run during times of slow business activity. User can also
determine the order in which tasks run by creating job steps within a SQL Server Agent job. E.g. back up
database, Update Stats of Tables. Job steps give user control over flow of execution. If one job fails, user
can configure SQL Server Agent to continue to run the remaining tasks or to stop execution.
What are the advantages of using Stored Procedures?

1. Stored procedure can reduced network traffic and latency, boosting application performance.
2. Stored procedure execution plans can be reused, staying cached in SQL Server's memory,
reducing server overhead.
3. Stored procedures help promote code reuse.
4. Stored procedures can encapsulate logic. You can change stored procedure code without affecting
clients.
5. Stored procedures provide better security to your data.
Stored Procedures
Stored Procedures are pre-compile objects which are compiled for first time and its compiled
format is saved which executes (compiled code) whenever it is called. But Function is compiled and
executed every time when it is called. For more about stored procedure and function refer the
articles Different types of Stored Procedure and Different types of Function.

Basic Difference

1.Function must return a value but in Stored Procedure it is optional( Procedure can return zero or n
values).
2.Functions can have only input parameters for it whereas Procedures can have input/output
parameters .
3.Function takes one input parameter it is mandatory but Stored Procedure may take o to n input
parameters..
4.Functions can be called from Procedure whereas Procedures cannot be called from Function.

Advance Difference

1.Procedure allows SELECT as well as DML(INSERT/UPDATE/DELETE) statement in it whereas


Function allows only SELECT statement in it.
2.Procedures can not be utilized in a SELECT statement whereas Function can be embedded in a
SELECT statement.
3.Stored Procedures cannot be used in the SQL statements anywhere in the
WHERE/HAVING/SELECT section whereas Function can be.
4.Functions that return tables can be treated as another rowset. This can be used in JOINs with
other tables.
5.Inline Function can be though of as views that take parameters and can be used in JOINs and
other Rowset operations.
6.Exception can be handled by try-catch block in a Procedure whereas try-catch block cannot be
used in a Function.
7.We can go for Transaction Management in Procedure whereas we can't go in Function.
/*
DECLARE @OutPutValue VARCHAR(100)
EXEC spExample 'CodeProject', @OutPutValue OUTPUT
PRINT @OutPutValue
*/
CREATE PROCEDURE [dbo].[spExample]
@parameter1 VARCHAR(100)
,@parameter2 VARCHAR(200) OUTPUT
AS
BEGIN
DECLARE @parameter3 VARCHAR(100)
SET @parameter3 = ' Your development resources.'
IF @parameter1 IS NOT NULL AND LEN(@parameter1) > 1
SELECT @parameter2 = 'The '
+ @parameter1
+ @parameter3
ELSE SELECT @parameter2 = 'CodeProject is cool!'
RETURN
END
GO

Statement
INSERT INTO table_name (column1,column2,column3,...)
VALUES (value1,value2,value3,...);

UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;

DELETE FROM table_name


WHERE some_column=some_value;

SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate


FROM Orders
INNER JOIN Customers
ON Orders.CustomerID=Customers.CustomerID;

SELECT Customers.CustomerName, Orders.OrderID


FROM Customers
INNER JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;

SELECT Customers.CustomerName, Orders.OrderID


FROM Customers
LEFT JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;

SELECT Orders.OrderID, Employees.FirstName


FROM Orders
RIGHT JOIN Employees
ON Orders.EmployeeID=Employees.EmployeeID
ORDER BY Orders.OrderID;

SQL FULL OUTER JOIN Example


The following SQL statement selects all customers, and all orders:
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
FULL OUTER JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;

What is the need of WPF when we had windows forms?

A - Anywhere execution ( Windows or Web)


B - Bindings ( less coding)
C - Common look and feel ( resource and styles)
D - Declarative programming (XAML)
E - Expression blend animation ( Animation ease)
F - Fast execution ( Hardware acceleration)
G - Graphic hardware independent ( resolution independent)
What is XAML in WPF and why do we need it?
XAML is a XML file which represents your WPF UI. The whole point of creating the UI representation in
XML was write once and run it anywhere. So the same XAML UI can be rendered as windows application
with WPF and the same UI can be displayed on the browser using WPF browser or Silverlight
application.

What is xmlns in XAML file?


“xmlns” stands for XML namespaces. It helps us to avoid name conflicts and confusion in XML
documents. For example consider the below two XML which have table elements, one table is a HTML
table and the other represents a restaurant table. Now if both these elements come in a single XML
document there would name conflicts and confusion.

<table>
<tr><td>Row1</td></tr>
<tr><td>Row2</td></tr>
</table>

===============================

<table>
<cloth>red</cloth>
<serve>Tea</serve>
</table>

So to avoid the same we can use XML namespaces. You can see in the below XML we have qualified the
HTML table with “” and the restaurant table element qualified with “”.
<h:table xmlns:h="http://www.w3.org/TR/html4/">
<tr><td>Row1</td></tr>
<tr><td>Row2</td></tr>
</h:table>

================================

<r:table xmlns:h="http://www.questpond.com/restaurant/table/def">
<cloth>red</cloth>
<serve>Tea</serve>
</r:table>

What is the difference between xmlns and xmlns:x in WPF ?


Bothe namespaces helps to define / resolved XAML UI elements.
The first namespace is the default namespace and helps to resolve overall WPF elements.
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
The second namespace is prefixed by “x:” and helps to resolve XAML language definition.

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
For instance for the below XAML snippet , we have two things one is the “StackPanel” and the other is
“x:name”. “StackPanel” is resolved by the default namespace and the “x:name” is resolved by using
“xmlns:x” namespace.

<StackPanel x:Name="myStack" />

What are the different kinds of controls in WPF?


WPF controls can be categorized in to four categories:-
•Control: - This is the basic control with which you will work most of time. For example textbox,
buttons etc. Now controls which are standalone control like button , text box , labels etc are termed
as content control. Now there are other controls which can hold other controls, for instance
itemscontrols. Itemscontrol can have multiple textbox controls, label controls etc.
•Shape: - These controls help us to create simple graphic controls like Ellipse, line, rectangle etc.
•Panel: - These controls help to align and position the controls. For instance grid helps us to align in
a table manner, stack panel helps for horizontal and vertical alignment.
•Content presenter: - This control helps to place any XAML content inside it. Used when we want
to add dynamic controls on a WPF screen.
All the above four types of WPF controls finally inherit from the frameworkelement class of WPF.

Can you explain the complete WPF object hierarchy?


Object: - As WPF is created using .NET so the first class from which WPF UI classes inherits is
the .NET object class.
Dispatcher: - This class ensures that all WPF UI objects can be accessed directly only by the thread
who own him. Other threads who do not own him have to go via the dispatcher object.
Dependency: - WPF UI elements are represented by using XAML which is XML format. At any
given moment of time a WPF element is surrounded by other WPF elements and the surrounded
elements can influence this element and this is possible because of this dependency class. For
example if a textbox surrounded by a panel, its very much possible that the panel background color
can be inherited by the textbox.
Visual: - This is the class which helps WPF UI to have their visual representation.
UI Element: - This class helps to implement features like events, input, layouting etc.
Framework element: - This class supports for templating , styles , binding , resources etc.
And finally all WPF controls textbox , button , grids and whatever you can think about from the
WPF tool box inherits from the framework element class.
Does that mean WPF has replaced DirectX?
No, WPF does not replace DirectX. DirectX will still be still needed to make cutting edge games.
The video performance of directX is still many times higher than WPF API. So when it comes to
game development the preference will be always DirectX and not WPF. WPF is not an optimum
solution to make games, oh yes you can make a TIC TAC TOE game but not high action animation
games.
One point to remember WPF is a replacement for windows form and not directX.
So is XAML meant only for WPF ?
No,XAML is not meant only for WPF.XAML is a XML-based language and it had various variants.
WPF XAML is used to describe WPF content, such as WPF objects, controls and documents. In
WPF XAML we also have XPS XAML which defines an XML representation of electronic
documents.
Silverlight XAML is a subset of WPF XAML meant for Silverlight applications. Silverlight is a
cross-platform browser plug-in which helps us to create rich web content with 2-dimensional
graphics, animation, and audio and video.
WWF XAML helps us to describe Windows Workflow Foundation content. WWF engine then uses
this XAML and invokes workflow accordingly.
Can you explain the overall architecture of WPF?
Above figure shows the overall architecture of WPF. It has three major sections presentation core,
presentation framework and milcore. In the same diagram we have shown how other section like
direct and operating system interact with the system. So let’s go section by section to understand
how every section works.
User32:- It decides which goes where on the screen.
DirectX: - As said previously WPF uses directX internally. DirectX talks with drivers and renders
the content.
Milcore: - Mil stands for media integration library. This section is a unmanaged code because it acts
like a bridge between WPF managed and DirectX / User32 unmanaged API.
Presentation core :- This is a low level API exposed by WPF providing features for 2D , 3D ,
geometry etc.
Presentation framework:- This section has high level features like application controls , layouts .
Content etc which helps you to build up your application.
What is App.xaml in WPF project?
App.xaml is the start up file or a boot strapper file which triggers your first XAML page from your
WPF project.
What are various ways of doing alignment in WPF?
There are five ways of doing alignment in WPF:-
Grid:- In Grid alignment we divide the screen in to static rows and columns like HTML tables and
position elements in those rows and column area.
<Grid>

<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>

<Label Grid.Column="0" Grid.Row="0" Background="Red">1st column 1st row </Label>

<Label Grid.Column="1" Grid.Row="0" Background="LightGreen">2nd Column 2nd row</Label>


<Label Grid.Column="0" Grid.Row="1" Background="Red">1st column 2nd row</Label>
<Label Grid.Column="1" Grid.Row="1" Background="LightGreen">2nd Column 2nd row</Label>

</Grid>

Stack panel :- Arranges control in vertical or horizontal format.


<StackPanel Orientation="Vertical">
<Label Background="Red">Red </Label>
<Label Background="LightGreen">Green </Label>
<Label Background="LightBlue">Blue </Label>
<Label Background="Yellow">Yellow </Label>
</StackPanel>

WrapPanel :-Aligns elements in a line until the border is hit , then wraps in to the next line.
<WrapPanel Orientation="Horizontal">
<Label Width="125" Background="Red">Red 1</Label>
<Label Width="100" Background="LightGreen">Green 1</Label>
<Label Width="125" Background="LightBlue">Blue 1</Label>
<Label Width="50" Background="Yellow">Yellow 1</Label>
<Label Width="150" Background="Orange">Orange 1</Label>
<Label Width="100" Background="Red">Red 2</Label>
<Label Width="150" Background="LightGreen">Green 2</Label>
<Label Width="75" Background="LightBlue">Blue 2</Label></WrapPanel>

Dock Panel: - Aligns controls in five different regions: top, bottom, left, right and center.

<DockPanel>
<Label DockPanel.Dock="Top" Height="100" Background="Red">Top 1</Label>
<Label DockPanel.Dock="Left" Background="LightGreen">Left</Label>
<Label DockPanel.Dock="Right" Background="LightCyan">Right</Label>
<Label DockPanel.Dock="Bottom" Background="LightBlue">Bottom</Label>
<TextBlock VerticalAlignment="Center" HorizontalAlignment="Center"> Demo of Dock
panel</TextBlock>
</DockPanel>

What are resources in WPF?


Resources are objects referred in WPF XAML. In C# code when we create an object we do the following
three steps :-
Collapse | Copy Code

using CustomerNameSpace; // import the namespace.

Customer obj = new Customer(); // Create object of the class

Textbox1.text = obj.CustomerCode; // Bind the object with UI elements

So even in WPF XAML to define resources which are nothing but objects we need to the above 3 steps :-
•Import namespace where the class resides: - To define namespace we need to use the “xmlns” attribute
as shown in the below XAML code.
Collapse | Copy Code
<Window x:Class="LearnWpfResources.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:custns="clr-namespace:LearnWpfResources"
Title="MainWindow" Height="350" Width="525">

•Create object of the class :- To create an object of the class in XAML we need to create a resource by
using the resource tag as the below code. You can the object name is ‘custobj”.
Collapse | Copy Code
<Window.Resources>
<custns:Customer x:Key="custobj"/>
</Window.Resources>

The above code you can map to something like this in C#


Collapse | Copy Code
Customer custobj = new Customer();
•Bind the object with UI objects :- Once the object is created we can then bind them using bindings like
one way , two way as explained in “Explain one way, two way, one time and one way to source?”
question explained above.
Collapse | Copy Code
<TextBox Text="{Binding CustomerCode, Mode=TwoWay, Source={StaticResource custobj}}" />

Explain the difference between static and


dynamicresource?
Resources can be referred statically or dynamically. Static referred resources evaluate the resource only
once and after that if the resources change those changes are not reflected in the binding. While
dynamic referred resources are evaluated every time the resource is needed.
Consider the below “SolidColorBrush” resource which is set to “LightBlue” color.
Collapse | Copy Code
<Window.Resources>
<SolidColorBrush Color="LightBlue" x:Key="buttonBackground" />
</Window.Resources>

The above resource is binded with the below two textboxes statically and dynamically respectively.
Collapse | Copy Code
<TextBox Background="{DynamicResource buttonBackground}" />
<textbox background="{StaticResource buttonBackground}">

Now if we modify the resource , you see the first text box changes the background and the other
textbox color stays as it is.
Collapse | Copy Code
private void Button_Click(object sender, RoutedEventArgs e)
{
Resources["buttonBackground"] = Brushes.Black;
}

Below is the output of the same.

When should we use static resource over dynamic


resource ?
Dynamic resources reduce application performance because they are evaluated every time the resource
is needed. So the best practice is use Static resource until there is a specific reason to use dynamic
resource. If you want resource to be evaluated again and again then only use dynamic resource.

Explain the need of binding and commands?


WPF Binding’s helps to send / receive data between WPF objects while command helps to send and
receive actions.The object that emits data or action is termed as source and the object who wants to
receive data or action is termed as target.

Explain one way, two way, one time and one way to
source?
All the above 4 things define how data will flow between target and source objects when WPF binding is
applied.
Two way: - Data can flow from both source to target and from target to source.
One way: - Data flows only from source to target.
One way to source: - Data flows only from target to source.
One time: - Data flows only for the first time from source to target and after that no communication
happens.

Below is an easy tabular representation to memorize the same.


One way to source

Data flow
Bindings Target to Source Source target
Two way Yes Yes
One way to source Yes No
One way No Yes
One time No For first Yes

Can you explain WPF command with an example?


When end users interact with application they send actions like button click, right click , control + c,
control + v etc. A command class in WPF wraps these end user actions in to a class so that they can be
reused again and again.
WPF Command class idea is an implementation of command pattern from gang of four design pattern.
To create a command class we need to implement the “ICommand” interface. For example below is a
simple command class which increments a counter class by calling “Increment” method.
Collapse | Copy Code
public class IncrementCounter : System.Windows.Input.ICommand
{
private clsCounter obj;
public IncrementCounter(clsCounter o)
{
obj = o;
}
public bool CanExecute(object parameter)
{
return true;
}

public event EventHandler CanExecuteChanged;

public void Execute(object parameter)


{
obj.Increment();
}
}

The command class needs two implement two methods as shown in the above code:-
What to Execute (Execute) – Command class is all about wrapping actions of end users so that we can
reuse them. At the end of the day Action invokes methods. Mean for instance a “btnmaths_click” action
will invoke “Add” method of a class. The first thing we need to specify in the command class is which
method you want to execute. In this case we want to call the “Increment” method of “clsCounter” class.
When to execute (CanExecute) – The second thing we need to specify is when the command can
execute, means validations. This validation logic is specified in the “CanExecute” function. If the
validation returns true then “Execute” fires or else the action has no effect.
You can see the code of “CanExecute” and “Execute” in the above code snippet.
Once you have created the “Command” class you can bind this with the button using the “Command”
property as shown in the below XAML code.”CounterObj” is a resource object.
Collapse | Copy Code
<Button Command="{Binding IncrementClick, Source={StaticResource Counterobj}}"/>
So now that the action is wrapped in to command we do not need to write method invocation code
again and again in behind code, we just need to bind the command object with the WPF UI controls
wherever necessary.

How does “UpdateSourceTrigger” affect bindings?


“UpdateSourceTrigger” decides when the data should get updated between WPF objects that are
binded. In other word should data get updated in lost focus event, in data change event etc.
There are four modes by which “UpdateSourceTrigger” can be defined:-
•Default: - If it’s a text property then data is updated during lost focus and for normal properties data
updates in property change event.
•PropertyChanged: - In this setting data is updated as soon as the value is changed.
•LostFocus: - In this setting data is updated as soon as lost focus event occurs.
•Explicit: - In this setting the data is updated manually. In other words to update data between two WPF
object you need to call the below code.
Collapse | Copy Code

BindingExpression binding =txt1.GetBindingExpression(TextBox.TextProperty);


binding.UpdateSource();

To set “UpdateSourceTrigger” we need to use the “UpdateSourceTrigger” value which can be found in
the bindings properties as shown in the below figure.

Explain the need of “INotifyPropertyChanged”


interface?
When we bind two WPF objects the target data is updated depending on the “UpdateSourceTrigger”
events. Please refer the previous question for “UpdateSourceTrigger” basics.
The “UpdateSourceTrigger” has events like lostfocus , property change etc. In other words when
lostfocus or property change event happen on the target it makes a PULL to the source to get the latest
data.

So it’s very much possible that the WPF source data has changed and because the WPF target
“UpdateSourceTrigger” event did not fire he did not make a pull and the data of the source is not in
synch with the target. This is where “INotifyPropertyChanged” interface comes to use.

Below is a simple “clsCounter” class which has a “Counter” property and this property is incremented by
“Increment” method.
Now if we bind WPF label or textbox to the “Counter” property and call the “Increment” method the
new “Counter” value will not be propagated to the target. Because invoking a method does not trigger
any “UpdateSourceTrigger” event.
So after calling the “Increment” method the “Counter” value of the source and the target are out of
synch.
So create a push event from the source you need to first implement “INotifyPropertyChanged” interface
as shown in the below figure. Now when someone calls the “Increment” method you can raise an event
saying that the “Counter” property has changed by calling “PropertyChanged” function as shown in the
below code.
In simple words the source sends a notification to the target WPF object that data has changed in the
source and he should refresh himself with the fresh data.
Collapse | Copy Code
PropertyChanged(this, new PropertyChangedEventArgs("Counter"));
Below is full “clsCounter” class code with “INotifyPropertyChanged” implemented.
Collapse | Copy Code
public class clsCounter : INotifyPropertyChanged
{

private int _Counter=0;

public int Counter


{
get { return _Counter; }
}

public void Increment()


{
_Counter++;
PropertyChanged(this, new PropertyChangedEventArgs("Counter"));
}

public event PropertyChangedEventHandler PropertyChanged;


}

What are value converters in WPF?


Binding is one of the big features in WPF which helps us to facilitate data flow between WPF UI and
Object. But when data flows from source to UI or vice-versa using these bindings we need to convert
data from one format to other format. For instance let’s say we have a “Person” object with a married
string property.

Let’s assume that this “married” property is binded with a check box. So if the text is “Married” it should
return true so that the option check box look’s checked. If the text is “Unmarried” it should return false
so that the option check box looks unchecked.
In simple words we need to do data transformation. This is possible by using “Value Converters”. In
order to implement value converters we need to inherit from “IValueConverted” interface and
implement two methods “Convert” and “ConvertBack”.
Collapse | Copy Code
public class MaritalConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
string married = (string)value;
if (married == "Married")
{
return true;
}
else
{
return false;
}
}

public object ConvertBack(object value, Type targetType, object parameter,


System.Globalization.CultureInfo culture)
{
bool married = (bool)value;
if (married)
{
return "Married";
}
else
{
return "UnMarried";
}
}
}

You can see in the “Convert” function we have written logic to transform “Married” to true and from
“Unmarried” to false. In the “Convertback” function we have implemented the reverse logic.

Explain multi binding and multivalue converters in


WPF?
“MultiBinding” helps you bind multiple sources to a target while multi-converters acts like bridge if the
source and targets have different data formats or need some conversion.

For example let’s say you have two textboxes which has “FirstName” and “LastName”. You want that as
soon as users type on these two textboxes, the other text box should get updated with
“FirstNameLastName” ( As shown in the below figure).
Also vice versa if we type in the third text box “FirstNameLastName” it should display “FirstName” and
“LastName’ in the other two textboxes respectively.

So the first thing is to create a multivalue converter class which will join “FirstName” and “LastName” in
to source and split “FirstNameLastName” back to target. For the same we need to implement
“IMultiValueConverter” and implement “Convert” and “ConvertBack” methods.
“Convert” helps to do conversion from “Target” to “Source” and “ConvertBack” helps to convert from
“Source” to “Target”.
Collapse | Copy Code
public class NameMultiConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
// Conversion logic from Target to Source
}

}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter,
System.Globalization.CultureInfo culture)
{
// Conversion logic from Source to Target.
}
}

Below is the “Convert” ( Target to Source) implementation where we get the “textbox” value in a array
and we have concatenated the array values and returned the same in a single string. This single string
will be displayed in the third textbox.
Collapse | Copy Code
public object Convert(object[] values, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
string x = "";
foreach (object y in values)
{

x = x + " " + y.ToString();


}
return x;
}

“ConvertBack” helps to implement conversion logic from “Source” to “Target”. So when someone types
“Shiv Koirala” in the third text box we would like to split “Shiv” in one string and “Koirala” in other string.
So you can see in the below code we have used the “Split” function to create a string array. So the first
array index ( array[0]) will go to the first textbox and the second array index (array[1]) will go to the
second text box.
Collapse | Copy Code
public object[] ConvertBack(object value, Type[] targetTypes, object parameter,
System.Globalization.CultureInfo culture)
{
string str = (string)value;
string[] val = str.Split(' ');

return val;
}

Now once we are done with the converter next thing is to apply multi-binding. Below is the XAML code
where we have the three text boxes “txtFirstName” , “txtLastName” and “txtFirstAndLast”.
You can see how the “txtFirstAndLast” textbox “Text” is binded using multibinding element which binds
to “txtFirstName” and “txtLastName” textbox . So now if you make changes to multiple target the single
source gets updated and if you update the source multiple target gets updates.
Collapse | Copy Code
<TextBox x:Name="txtFirstName" HorizontalAlignment="Left" Height="26" Margin="42,67,0,0"
TextWrapping="Wrap" Text=""

VerticalAlignment="Top" Width="152"/>

<TextBox x:Name="txtLastName" HorizontalAlignment="Left" Height="26" Margin="41,135,0,0"


TextWrapping="Wrap" Text=""

VerticalAlignment="Top" Width="153"/>

<TextBox x:Name="txtFirstAndLast" Height="28" HorizontalAlignment="Left" Margin="239,103,0,0"


Name="label1"

VerticalAlignment="Top" Width="117">
<TextBox.Text>
<MultiBinding Converter="{StaticResource NameMultiConverter}">
<Binding ElementName="txtFirstName" Path="Text" />
<Binding ElementName="txtLastName" Path="Text" />
</MultiBinding>
</TextBox.Text>
</TextBox>

Explain WPF relative binding / relative resource?


When we define bindings we need at least two elements target and source. But many times rather than
defining binding between two elements we would like to define binding with reference to the current
element i.e. RELATIVELY.
For instance let’s say we have a WPF border and we would like height and width of the broder to be
same. So for this scenario the target and source are the same, the WPF border itself. So we can define
the binding using “RelativeSource” as shown in the below code. You can see it uses “Self” binding mode
to bind the element to itself.
Collapse | Copy Code
<Border BorderBrush="Black" BorderThickness="1" Height="139"
Width="{Binding Height, RelativeSource={RelativeSource Self}}"/>

What are the different ways of binding using relative


source?
There are four ways of binding relatively in WPF :-
•Self
•Ancestor
•Previousdata
•Templated parent

Can you explain self relative source binding in


WPF?
This relative binding helps to bind to one property of an element to the other property of the same
element. For example in the below XAML the border width is binded to height of the same border
element.
Collapse | Copy Code
<Border BorderBrush="Black" BorderThickness="1" Height="139"
Width="{Binding Height, RelativeSource={RelativeSource Self}}"/>

Explain Ancestor relative source binding in WPF?


This relative binding helps to bind properties to the parent element properties. For example in the
below XAML code we have a textbox which has two border’s as a parent. One border is having dark
green and the other border is having dark red color as the border color.
The dark green color border is the parent element followed by dark red and the text box the child
element at the end of the hierarchy.
Collapse | Copy Code
<Border BorderBrush="DarkGreen">
<Border BorderBrush="DarkRed”>
<TextBox />
</Border>
</Border>
Below is how the WPF application looks like when it runs.

Now we want the background color of the text box to be binded to one of the parent border colors. To
achieve the same we can use ancestor relative binding.
Below are some important properties in Ancestor type binding we need to know before we writing the
binding code.

Property Description
Which type of parent element is it?. Is it a border element , grid element
AncestorType
etc.
An element can have multiple parents. For example in the above XAML we
have two parents one with red color and the other with green. So this
property specifies which level of parent element we want to refer. Below
AncestorLevel
is the figure which depicts the levels. The red color border is level 1 and
the green color border is level 2.
So the nearest element becomes the first level and so on.
This specifies which property we want to bind to. For the current example
Binding
we want to bind to border’s brush color.

So the relative binding code with ancestor level 1 i.e. red looks as shown below. In case you are
confused with any of the properties please refer to the previous table for more information.
Collapse | Copy Code
<TextBox Background="{Binding BorderBrush, RelativeSource={RelativeSource FindAncestor,
AncestorLevel=1, AncestorType={x:Type Border}}}"/>
So now the complete XAML with parent border element looks as shown in the below code.
Collapse | Copy Code
<Border BorderBrush="DarkGreen"><!-- Level 2 ->
<Border BorderBrush="DarkRed”><!-- Level 1 ->

<TextBox removed="{Binding BorderBrush, RelativeSource={RelativeSource FindAncestor,


AncestorLevel=1, AncestorType=

{x:Type Border}}}"/>

</Border>
</Border>

Now if you run the above XAML code the textbox is binded with the back ground color of the first
border. If you change the ancestor level to 2 textbox background color will change to green.

PreviousData
Collapse | Copy Code
<ItemsControlItemsSource="{Binding}" Margin="10">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlockFontSize="14"FontWeight="bold"
Margin="20"
Text="{Binding Value}" removed="Aqua">
</TextBlock>
<TextBlockFontSize="14"FontWeight="bold"
Margin="20"
Text="{Binding
RelativeSource={RelativeSourcePreviousData},
Path=Value}" removed="Blue">

</TextBlock>

</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>

publicclassItem : INotifyPropertyChanged
{
privatedouble _value;

publicdouble Value
{
get { return _value; }
set { _value = value; OnPropertyChanged("Value"); }
}

#regionINotifyPropertyChanged Members

publiceventPropertyChangedEventHandlerPropertyChanged;

#endregion

protectedvoidOnPropertyChanged(stringPropertyName)
{
if (null != PropertyChanged)
{
PropertyChanged(this,
newPropertyChangedEventArgs(PropertyName));
}
}
}
publicclassItems : ObservableCollection<Item>
{
public Items()
{
Add(newItem { Value = 80.23 });
Add(newItem { Value = 126.17 });
Add(newItem { Value = 130.21 });
Add(newItem { Value = 115.28 });
Add(newItem { Value = 131.21 });
Add(newItem { Value = 135.22 });
Add(newItem { Value = 120.27 });
Add(newItem { Value = 110.25 });
Add(newItem { Value = 90.20 });
}
}

Explain the difference between visual and logical


tree in WPF ?
WPF UI is represented in XAML which is a XML format. In XML elements are arranged in a hierarchal
fashion. For example if you look at the below XAML (it has been downsized for simplicity) we have a
Window element, the window element has a Grid control and the grid control has a button inside it.
Collapse | Copy Code
<Window>
<Grid>
<Button..>
</Grid>
</Window>

So if you visualize the above XAML logically you can think that the button control is a child element of
the Grid and the grid is the child element of the Window. This relationship between the elements which
looks logical looking at the XAML is termed as “Logical tree”.

But now to display this Logical tree on to your screen you need lot of visual elements. like border, text
etc. So when you add these visual elements to the logical tree that complete structure is termed as
“Visual Tree”.
Putting in simple words there is only tree in WPF but depending on how you view it these two trees are
the outcome. If you use the WPF visualizer the above XAML tree looks something as shown in the below
figure which is actually a complete visual tree.
In simple words whatever you see in your XAML is a logical tree and to make it display it uses the visual
tree. Below is an in detail figure which shows the logical and visual tree of the above XAML. Logical tree
is without the shades and with shades is the visual tree.

Why do we need to have these perspective of visual


and logical tree in WPF ?
Visual tree and Logical tree are important when you work with WPF routed events.

Explain routed events in WPF?


Routed events are those events which travel up or down the visual tree hierarchy. WPF events can be
classified in to 3 types:-
Direct events: - In this case event is raised at the source and handled at the source itself like
“MouseEnter” events.
Bubbling events: - They travel up the visual tree hierarchy. For example “MouseDown” is a bubbling
event.
Tunneling events: - These events travel down the visual tree hierarchy. “PreviewKeyDown” is a tunneling
event.

What are styles in WPF?


WPF style helps to define look and feel ( color , fonts, alignments etc) from a central location so that we
can have ease of maintenance.For more details on WPF styles please check this link out which also
has simple sample WPF examples

What are style triggers?


Many times we would want a style property to execute under certain conditions. Trigger’s help you to
define condition under which the style values will be set.
For instance in the below XAML code we have style trigger defined for button which set’s background
color to “Red” if there is focus on the button or else the back ground color is set to “Aqua”.
Collapse | Copy Code
<Style x:Key="myStyle" TargetType="Button">
<Style.Triggers>
<Trigger Property="IsFocused" Value="True">
<Setter Property="Background" Value="Red"/>
</Trigger>
</Style.Triggers>
<Setter Property="Background" Value="Aqua" />
</Style>

What is MVVM?
MVVM is an architecture pattern where we divide the project in to three logical layers and every layer
has its own responsibility.

Below are the three logical layers with explanation what they do:-
•View: - This layer handles responsibility of taking inputs from end user, positioning of controls, look
and feel, design, visuals, colors etc.
•Model: - This layer represents your middle layer objects like customer, supplier etc. It handles business
logic and interaction with data access layer.
•View Model: - View model as it says View plus model represents your user interface. You can also
visualize this class as the behind code. This class is the bridge between model and view. It handles
connection logic , data transformation logic and action mapping between model and view. For example
it will have following types of logics as shown below :-
•Replicating and propagating data between views and models. When someone enters data in to UI or
the model gets updated this layer will ensure that the propagation of data happens between these
entities.
•Handling data transformation from view to model and vice versa. For example you have a model which
has gender property with data as “M” for male and “F” for female. But on the View or UI you would like
to display as a check box with true and false. This transformation logic is written in the view model class.
•View model also map UI actions to methods. For example you have “btn_Add” click event and when
any one clicks on this button you would like to invoke “Customer.Add()” method from the customer
class. This connection code is again a part if view model.

What are the benefits of MVVM?


Below are the benefits of MVVM pattern:-
Separation of concern: - As the project is divided in to layers, every layer handles its own responsibility.
This leads to better maintenance because when we change one layer the other layer does not get
affected.
Increased UI Reusability: - The whole point of MVVM is to remove behind code i.e. XAML.CS code. The
problem with behind code is that it is tied up with a UI technology for example ASPX.CS code is tied up
with the ASP page class, XAML.CS file is tied with WPF UI technology and so on. So we cannot use
ASPX.CS behind code with WPF XAML UI.
By moving the behind code to the view model class we can now use this with any UI technology.

Automated UI Unit testing: - View model class represents your UI. The properties of the class represent
UI text boxes, combo boxes and the methods of the class represent action. Now as the UI is represented
by the view model class, we can do automated UI testing using unit testing by creating the objects of
view model class and doing the necessary asserts.

What is the importance of command and bindings in


MVVM pattern?
MVVM in the most used architecture because of command and bindings facility provided by WPF. WPF
MVVM is incomplete without command and bindings.

Command and bindings helps you to connect view (WPF UI) with view model class without writing lot of
behind code. Binding connects the UI input elements (textbox, combo box etc.) with the view model
class properties and the UI actions like button click, right click are connected to the methods of the class
by commands.
Collapse | Copy Code
Note :- Please refer previous questions to understand command and bindings.

What is the difference between MVVM and 3 layer


architecture?
MVVM has an extra layer as compared to 3 layer architecture. In 3 layer architecture we have UI (view) ,
business logic ( model) and Data access layer ( DAL). In MVVM we have an extra layer in between view
and model i.e. the view model class.
3 layer architecture complements MVVM architecture.
Explain delegate command?
First let us answer in short: - “Delegate command makes a MVVM command class independent of the
view model”.Now let’s understand the long way.
In MVVM architecture view talks with the view model and view model talks with the model. When
actions are sent from the view they are sent to WPF commands for handling the events. WPF commands
invoked methods of view model internally.
In other words command needs reference of view model class.

If you see a typical WPF MVVM command it looks as shown below. You can see the
“CustomerViewModel” class referenced inside the ‘btnCommand” class. If you think with your eyes
closed this reference of “CustomerViewModel” class inside the command is a problem. This will lead to
tight coupling between command classes and view model.
If you visualize command it is nothing but click , double click , left mouse click , drag and drop etc. It’s
an ACTION created by the user. Now wouldn’t be great if we can just attach this command with any
view model. So like click event gets connected with “CustomerViewModel” or “SupplierViewModel”.
This is achieved by using delegate command.
Collapse | Copy Code

public class btnCommand : ICommand


{
Private CustomerViewModel Viewobj = new CustomerViewModel();

public btnCommand(CustomerViewModel obj)


{
Viewobj = obj;
}
public bool CanExecute(object parameter) // When he should execute
{
return Viewobj.IsValid();
}

public void Execute(object parameter) // What to execute


{
ViewObj.Add();
}
}

To decouple the view model class from command we can use delegates i.e. “Action” and “Func”. If you
see the command class we need only two things “WhattoExecute” and “WhentoExecute”. So how about
passing these methods as generic delegates. You can see the constructor of “btnCommand” takes two
delegates one what to execute and when to execute.
You can see in the below code the “btnCommand” class has no reference of the view model class but
has references to delegates which are just abstract pointer to functions / methods. So this command
class can now be attached with any view model class. This approach is termed as “Delegate command”.
Collapse | Copy Code
public class btnCommand : ICommand // Step 1 :- Create command
{
private Action WhattoExecute;
private Func<bool> WhentoExecute;
public btnCommand(Action What , Func<bool> When)
{
WhattoExecute = What;
WhentoExecute = When;
}
public bool CanExecute(object parameter) // When he should execute
{
return WhentoExecute();
}

public void Execute(object parameter) // What to execute


{

WhattoExecute();
}
}

What is PRISM?
PRISM is a framework to develop composite application in WPF and Silverlight. Composite applications
are built using composition. In other words rather than building application from scratch we take
prebuilt components, assemble them together and create the application.

Take the below example of simple WPF UI. You can see it has lots of sections. Now rather than building
the whole UI as one big unit, we can develop all these section as independent unit. Later by using
PRISM we can compose WPF UI by taking all these independent units.

What are benefits of PRISM?


Modular development: - As we are developing components as independent units we can assign these
units to different developers and do modular parallel development. With parallel development project
will be delivered faster.
High reusability: - As the components are developed in individual units we can plug them using PRISM
and create composed UI in an easy way.

How are individual units combined in to a single


unit?
PRISM uses dependency injection for the same. Please see design pattern section to read about DI
(dependency injection). We can do DI by two way’s by using unity application block or MEF ( managed
extensibility framework).

Does PRISM do MVVM?


The prime focus of PRISM is modular development and not MVVM. But it does have readymade classes
like delegate command which can help us reduce MVVM code. But please note the main goal of PRISM
was not MVVM.

Is PRISM a part of WPF?


No, PRISM is a separate installation.
What is expression blend?
Expression blend is a designing tool for WPF and SilverLight application.

You might also like