Interview Questions All in One
Interview Questions All in One
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.
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.
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.
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.
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.
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.
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
set
_nameofcar = value;
}
get
return _nameofcar;
}
}
set
_colorofcar = value;
}
get
return _colorofcar;
}
}
Console.WriteLine("Streering of Car");
}
public void RearViewMirror()
Console.WriteLine("RearViewMirror of Car");
}
Console.WriteLine("Brakes of Car");
}
public void Gear()
Console.WriteLine("Gear of Car");
}
Console.WriteLine("InternalDetailsofCar of Car");
}
Console.WriteLine("CarEngine of Car");
}
Console.WriteLine("DiesalEngine of Car");
}
Console.WriteLine("ExhaustSystem of Car");
}
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.
class Employee{
private void AccountInformation(){
Console.WriteLine("Displaying Account Details");
}
class clsTelevision{
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
Abstraction and Encapsulation are two important Object Oriented Programming (OOPS) concepts.
Encapsulation and Abstraction both are interrelated terms.
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.
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;
4. Example of Abstraction
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.
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");
}
}
namespace abstractSample
{
//Creating an Abstract Class
abstract class absClass
{
//A Non abstract method
public int AddTwoNumbers(int Num1, int Num2)
{
return Num1 + Num2;
}
In the above sample, you can see that the abstract class absClass contains two
methods AddTwoNumbers 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;
}
}
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;
}
}
}
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();
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.
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.
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)
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();
}
}
}
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.
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.
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";
}
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…”);
}
}
We can use the "interface" as a pointer in the different layers of applications.We can use an interface
for implementing run time polymorphism.
Explicit
Implicit
To implement an interface explicitly we have to define an interface name followed by (".") dot
operator then the method name.
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
Multiple inheritance A class may inherit several A class may inherit only
interfaces. one abstract class.
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
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.
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.
// 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.
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);
return fahrenheit;
}
public static double FahrenheitToCelsius(string temperatureFahrenheit)
{
// Convert argument to double for calculations.
double fahrenheit = Double.Parse(temperatureFahrenheit);
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;
}
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.
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
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
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++;
}
private int x, y;
public static int objectCount = 0;
}
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));
}
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:
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.
// 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
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"); }
}
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:
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 { }
}
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.
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:
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();
t = 0;
foreach (int x in list)
{
t += x;
}
// No boxing, no casting
list1.Add(3);
list1.Add(1);
// Compile-time error:
list1.Add("This will trigger a Compile-time Error!");
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.
myInts.Add(1);
myInts.Add(2);
myInts.Add(3);
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 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
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
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 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
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.
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"
.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:
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.
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.
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.
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.
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.
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.
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.
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
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.
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.)
5.
What is Difference between NameSpace and Assembly?
• 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);
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:
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.
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.
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.
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.
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.
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.
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;
}
}
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;
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.
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.
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.
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.
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.
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.
The Response.Write() method allows you to write the normal output; whereas,
theResponse.Output.Write() method allows you to write the formatted output.
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.
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:
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.
• 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 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.
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" />
The trip of a Web page from the client to the server and then back to the client is known as a round trip.
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.
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.
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.
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.
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.
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.
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.
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.
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.
• 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 Global.asax file executes application-level events and sets application-level variables.
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.
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 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.
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.
• 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.
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.
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.
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.
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.
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.
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
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.
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.
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.
Model is normally responsible for accessing data from some persistent medium like database and
manipulate it.
routes.MapRoute(
"View", // Route name
"View/ViewCustomer/{id}", // URL with parameters
new { controller = "Customer", action = "DisplayCustomer", id
= UrlParameter.Optional }); // Parameter defaults
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") %>
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.
There 12 kinds of results in MVC, at the top is “ActionResult”class which is a base class that
canhave11subtypes’sas listed below: -
In the same way we have for other HTML controls like for checkbox we have “Html.CheckBox” and
“Html.CheckBoxFor”.
routes.MapRoute(
"View", // Route name
"View/ViewCustomer/{id}", // URL with parameters
new { controller = "Customer", action = "DisplayCustomer",
id = UrlParameter.Optional }); // Parameter defaults
[HttpGet]
public ViewResult DisplayCustomer(int id)
{
Customer objCustomer = Customers[id];
return View("DisplayCustomer",objCustomer);
}
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 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.
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 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:
<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 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:
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 ")
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.
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.
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.
UNION
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.
UNION ALL
UNION
SELECT * FROM EMPLOYEE WHERE ID = 5
GROUP BY dept.name
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
UNION
MINUS
INTERSECT
INTERSECT
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:
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.
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
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:
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.
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.
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
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
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;
<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>
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.
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
</Grid>
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>
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 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;
}
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.
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
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.
To set “UpdateSourceTrigger” we need to use the “UpdateSourceTrigger” value which can be found in
the bindings properties as shown in the below figure.
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
{
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;
}
}
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.
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)
{
“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"/>
VerticalAlignment="Top" Width="153"/>
VerticalAlignment="Top" Width="117">
<TextBox.Text>
<MultiBinding Converter="{StaticResource NameMultiConverter}">
<Binding ElementName="txtFirstName" Path="Text" />
<Binding ElementName="txtLastName" Path="Text" />
</MultiBinding>
</TextBox.Text>
</TextBox>
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 ->
{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 });
}
}
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.
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.
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.
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.
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
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();
}
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.