What are the different events which fire ASP.NET page life cycle?
Following is the sequence in which the events occur: -
- Init
- Load
- Validate
- Event
- Render
Note: - Remember word SILVER: - S(Start) I(Init) L(Load) V(Validate) E(Event) R(Render).
Page_init event only occurs when first time the page is started, but Page Load occurs in subsequent request of the page.
Can you explain how ASP.NET application life cycle works?
When
interviewer asks for page life the SILVER answer is appropriate, but
when interviewer is asking for application life cycle, two more things
come in to picture handlers and modules.
Below is how ASP.NET events fire.
- First the HttpModule events like BeginRequest, AuthenticateRequest fires.
- Then the HttpHandlers fires if the file extension matches of the request page name.
- Finally Page events fire i.e. in it, load , validate , event and render.
-----------------
How can we fire a simple SQL Statement using ADO?
- First imports the namespace “System.Data.SqlClient”.
- Create a connection object and call the “Open” function.
With objConnection
.Connection String = strConnectionString
.Open()
EndWith
- Create the command object with the SQL. Also, assign the created connection object to command object and execute the reader.
ObjCommand = New SqlCommand (“Select First Name from Employees”)
With objCommand
.Connection = objConnection
Breeder = .Execute Reader ()
EndWith
- You can then loop through the reader object to read the data.
Do while objReader.Read ()
lstData.Items.Add (objReader.Item (“First Name”))
Loop
- Do not forget to close the connection object.
objConnection.close*();
How do we use stored procedure in ADO.NET and how do we provide parameters to the stored procedures?
ADO.NET
provides the SqlCommand object, which provides the functionality of
executing stored procedures. In the command type we need to provide the
command type as stored procedure as shown in the below code snippet.
SqlCommand objCommand = new SqlCommand("sp_Insert", objConnection);
objCommand.CommandType = CommandType.StoredProcedure;
objCommand.ExecuteNonQuery();
How can we force the connection object to close after my data reader is closed?
Command
method Execute reader takes a parameter called as Command Behavior
wherein we can specify saying close connection automatically after the
Data reader is close.
PobjDataReader = pobjCommand.ExecuteReader (CommandBehavior.CloseConnection)
I want to force the data reader to return only schema of the data store rather than data.
PobjDataReader = pobjCommand.ExecuteReader (CommandBehavior.SchemaOnly)
----------------
What is the use of command objects?
Command object helps to execute SQL statements. Following are the methods provided by command object: -
- ExecuteNonQuery: -Executes insert, update and delete SQL commands. Returns an Integer indicating the number of rows affected by the query.
- ExecuteReader: - Executes select SQL statements which can either be in your .NET code or in a stored procedure. Returns a "Datareader" object.
- ExecuteScalar: - Executes SQL command and returns only a single value like count, sum, first record etc.
What are Dataset objects?
Dataset
is an in memory object with data tables, rows and columns. You can
visualize it as in-memory RDBMS. Dataset has the following features:-
- The in memory RDBMS works in a disconnected manner. In other words even if the connection is closed the dataset is still there in memory.
- You can do modification in the in-memory database object and send the final changes to the database.
Below
is a simple code snippet which shows how to access a column value. You
can see how the full dataset object hierarchy is accessed to get the
column value.
objDataset.Tables[0].Rows[0]["CustCode"]

------------------------
If we inherit a class do the private variables also get inherited?
Yes, the variables are inherited.
How can we stop the class from further inheriting?
We
can stop the class from further inheriting by using the "Sealed"
keyword. For instance below is a simple sample code where we have a
class called as "Human" which is further inherited to create a "Male" or
"Female" class.
Now
the below code is great but we do not anyone to further inherit from
"Male" or "Female" class. In simple words"Male" and "Female" are the
last legs in this inheritance hierarchy. This can be done by using the
"Sealed" keyword.
public class Human
{}
public sealed class Male : Human
{}
public sealed class Female : Human
{}
If anyone tries to inherit the sealed classes he will end with the below error "cannot derive from sealed type".
What is the use of “Must inherit” keyword in VB.NET?
If
you want to create an abstract class in VB.NET it’s done by using “Must
Inherit” keyword. You cannot create an object of a class, which is
marked as “Must Inherit”. When you define “Must Inherit” keyword for
class, you can only use the class by inheriting.
--------------------
What is a CLR?
CLR (Common language run time) is the heart of.NET framework and it does 4 primary important things: -
- Garbage collection
- CAS (Code Access Security)
- CV (Code verification)
- IL to Native translation.
Note:
- There are many other uses of CLR but I have kept it short from the
interview point of view. In the further section we will go in depth of
these questions.
What is a Garbage Collector?
Garbage
collector is a feature of CLR which cleans unused managed (it does not
clean unmanaged objects) objects and reclaims memory. It’s a back ground
thread which runs continuously and at specific intervals it checks if
there are any unused objects whose memory can be claimed.
Note: - GC does not claim memory of unmanaged objects.
What is code Access Security(CAS)?
CAS
is the part of .NET security model which determines whether or not a
particular code is allowed to run and what kind of resources can the
code access.
------------------
What are different access modifiers?
There are 5 access modifiers. Access modifiers define scope for members.
- Private: - Accessible only with in the class.
- Protected: -Accessible with in the class and in derived classes.
- Friend (internal in C#): -Accessible anywhere within the current project.
- Protected friend (protected internal in C#): - Accessible with current project and derived classes.
- Public: -Accessible everywhere.

Can we have different access modifiers on get/set methods of a property?
Yes, we can have different access modifiers. The below code will compile perfectly well.
public string CustName
{
get
{
return _Custname;
}
protected set
{
Custname = value;
}
}
-----------------
Object initializer in C#.
Does collection or object initializer affects the performance?
No, neither it increases performance nor decreases.
With Object initializer can we assign values to any properties?
Yes, considering it is accessible and not read only.
When working with Object initializers does the values will be assigned first or constructor gets called first?
Constructor will be called first.
Does object initializer only work with Properties?
No, we can even have fields.
How to make use of collection initializers with Dictionary?
We have to use key and value as follows: -
Dictionary<string,string>MyDictionary= new Dictionary<string,string>()
{
{"C11","V31"},
{"C12","V32"},
{"C13","V33"}
};
----------------
IL code, JIT, CLR, CTS, CLS and CAS
- IL code is a partially compiled code.
- JIT (Just in time compiler) compiles IL Code to machine language.
- CLR (Common language run time) is the heart of.NET framework and it does 4 primary important things Garbage collection, CAS (Code Access security), CV (Code verification) and IL to Native translation.
- CTS (Common types system) ensure that data types defined in two different languages get compiled to a common data type.
- CLS is a specification or set of rules or guidelines. When any programming language adheres to these set of rules it can be consumed by any .NET language.
- CAS is the part of .NET security model which determines whether or not a particular code is allowed to run and what kind of resources can the code access.
------------------
Classes and object in.NET using C#
What is a Class and object?
Class
is a blue print / template. Objects are instances of classes, in other
words they bring life in class. To use a class we need to create an
object.
What is nested Classes?
Nested classes are classes within classes.
What are abstract classes?
Abstract class is a half defined parent class. The full implementation of abstract class is defined by the child classes.
For
example below code snippet shows a simple abstract class / half defined
class called “DatabaseCommon” and later the concrete classes i.e.
“SQLServer” and “Oracle” inherit and define a complete implementation
for the same.
To define an abstract class we need to use the abstract keyword.
public abstract class DatabaseCommon
{
}
public class SQLServer : DatabaseCommon
{
}
public class Oracle : DatabaseCommon
{
}
-------------------
Online guide to learn .NET for Object initializer in C#?
Object
initializer let us create an instance of a class and assign values to
its properties in a single line. Normally we write following things
while working with classes and objects.
1. Create Object of class
Customer c=new Customer();
2. Assign values to its properties
c.CustomerName=”Sukesh Marla”;
c.Address=”Mumbai”;
But with object initializer we can do it in single line as follows
Customer c=new Customer()
{
CustomerName=”Sukesh Marla”,
Address=”Mumbai”
};
What does collection initializer do?
Just
like Object initializer it will reduce the work of a developer. It will
let us create an instance of any collection class and assign one or
more elements to it in the same line.
This is how we normally work,
1. Create instance of collection class.
List<int> collection=new List<int>();
2. Add elements to it
collection.add(1);
collection.add(2);
collection.add(3);
But with collection initializer we can do it in single line.
List<int> collection=new List<int>()
{
1,2,3
}
---------
Online resource to learn .NET on Reflection and Dynamic
Here we will look into differences between Reflection and Dynamic: -

---------
CTS and CLS
June 2, 2014 at 5:39pm
CTS (Common types system): -
In
.NET there are lots of languages like C#, VB.NET, VF.NET etc. There
can be situations when we want code in one language to be called in
other language. In order to ensure smooth communication between these
languages the most important thing is that they should have a common
type system. CTS (Common types system) ensure that data types defined in
two different languages get compiled to a common data type.
So “Integer” data type in VB6 and “int” data type in C++ will be converted to System.int32, which is data type of CTS.
Note: - If
you know COM programming, you would know how difficult it is to
interface VB6 application with VC++ application. As datatype of both
languages did not have a common ground where they can come and
interface, by having CTS interfacing is smooth.
CLS (Common Language Specification): -
CLS
is a subset of CTS. CLS is a specification or set of rules or
guidelines. When any programming language adheres to these set of rules
it can be consumed by any .NET language.
For
instance one of the rules which makes your application CLS
non-compliant is when you declare your methods members with same name
and with only case differences in C#. You can try this create a simple
class in C# with same name with only case differences and try to
consume the same in VB.NET ,it will not work.
-------------
In parent-child relationship which constructor will fire first and in which instances you will declare a co
How
to learn .NET: - In parent-child relationship which constructor will
fire first and in which instances you will declare a constructor
private?
Parent class constructor will fire first. Following is the code snippet: -
public class class1
{
public class1(){}
}
public class class2 : class1
{
public class2(){}
}
Declaring constructor to be private: -
When
we create a private constructor, we cannot create object of the class.
Private constructors are used when we want only a single instance of
the class to be created and externally no one can use the ‘new’ keyword
to create the object.
------------
Explain Generics and concept of Generic Collection in .NET?
Generics
help to separate logic and data type to increase reusability. In other
words you can create a class whose data type can be defined on run time.
For
instance below is a simple class “class1” with a “compareme” function
created using generics. You can see how the unknown data type is put in
greater than and less than symbol. Even the compare me method has the
unknown data type attached.
public class Class1<UNNKOWDATATYPE>
{
public bool Compareme(UNNKOWDATATYPE v1, UNNKOWDATATYPE v2)
{
if (v1.Equals(v2))
{
return true;
}
else
{
return false;
}
}
}
During runtime you can define the datatype as shown in the below code snippet.
Class1<int> obj = new Class1<int>();
bool b = obj.Compareme(1,2); // This compares numeric
Class1<string> obj1 = new Class1<string>();
bool b1 = obj1.Compareme("shiv","shiv"); // This does string comparison
Concept of Generic Collection in .NET: -
Array
List, Stack and Queues provide collections which are not type safe.
This leads 2 problems first it’s not type safe and second it leads to
boxing and unboxing.
By
using generics we can have type safety and also we can avoid boxing and
unboxing. Below is a simple code snippet which shows a strong typed
list of type integer and string.
List<int> obj;
obj.add(1); // you can only add integers to this list
List<string> obj;
obj.add(“shiv”); // you can only add string to this list
------------
What is Manifest? Where is the version information stored of an assembly? Is versioning applicable to private assemblies?
Assembly metadata is stored in Manifest. Manifest contains metadata which describes the following things -:
- Version of assembly.
- Security identity.
- Scope of the assembly.
- Resolve references to resources and classes.
The assembly manifest is stored in the DLL itself.
Storing version information of an assembly: -
Version information is stored in assembly inside the manifest.
Is versioning applicable to private assemblies: -
Yes, versioning is applicable to private assemblies also.
-------------
What is the difference between delegate and events? Can we have return type, access modifiers and shared events?
They cannot be compared because one derives from the other.
- Actually, events use delegates in bottom. But they add an extra layer of security on the delegates, thus forming the publisher and subscriber model.
- As delegates are function to pointers, they can move across any clients. So any of the clients can add or remove events, which can be confusing. But events give the extra protection / encapsulation by adding the layer and making it a publisher and subscriber model.
Just imagine one of your clients doing this
c.XyzCallback = null
This will reset all your delegates to nothing and you have to keep searching where the error is.
Events have return type: -
No, events do not have return type.
Do events have access modifiers: -
Yes.
Do we have shared events: -
Yes, you can have shared events; do note only shared methods can raise shared events.
---------------
How
abstract with only abstract method is it different from interfaces?
Also mention best practice to update interface with new methods?
If you define all methods, function, properties as abstract in abstract class it inhibits the same behavior as an interface.
Best practice to update interface with new methods: -
The
biggest use of interface is to ensure that strict CONTRACT is followed
between clients and components. So that when changes happen on the
components clients do not have to change too much. In real world
CONTRACTS between two parties do not change which implies that
interfaces should also not change.
So
if you want to add new methods or change methods in interfaces the best
practice is to create new interfaces by inheriting. With this approach
your older client who are using the interface stay happy and the new
clients who want those new or changed methods get the benefits of the
new functionality.
Let’s
consider you have a simple interface called as “IView” which helps you
to view data , below is the code for the same. Let’s consider that this
interface is consumed by many clients.
interface Iview
{
public void View();
}
Over
a period of time some users demand “Edit” functionality as well but the
rest of the users are happy with the ‘View” functionality and they do
not want them to get affected by these changes. Now if you go and change
this interface ( “IView”) a.k.a you will be disturbing everyone.

So
the best option would be to add a new interface i.e. “IEdit” which
inherits from “IView”. So the “IEdit” will have the functionality for
“Edit” as well as “View” because it’s also inheriting from “IView”. And
the clients who are consuming “IView” do not need to update as “IView’
is not changed at all.
interface IEdit : Iview
{
public void Edit();
}
So putting this whole story in one single sentence for the interviewer.
Interface
once fixed should not be changed. If we ever have to add new functions,
new interfaces should be created so that we do not break compatibility
with old clients.
-------------
What are the steps to fire a SQL DML statement from C#?
May 28, 2014 at 12:50pm
1. First you need SQL connection string
String
connectionString="Server=ServerAddress;Database=myDataBase;UserId=my
Username; Password=myPassword;";
2. Create an object of SqlConnection class as follows.
SqlConnection connection = new SqlConnection(connectionString)
3. Create an object of SQLCommand class as follows and assign query
SqlCommandcmd = new SqlCommand("Insert
inoEmployevalues(@Name,@Type,@Website) ");
4. Add parameters to it as follows.
cmd.Parameters.AddWithValues("@Name", “Sukesh Marla”);
cmd.Parameters.AddWithValues("@Type", “Trainer”);
cmd.Parameters.AddWithValues ("@Website", “www.Sukesh-Marla.com”);
5. Open the connection
connection.open();
6. Execute the query as follows
Cmd.ExecuteNonQuery();
7. Close the connection
Connection.Close();
What about the single value selection from SQL table?
It will also be a 7 step functionality like above only difference will be 6th step will be changed to follow.
String ReturnValue=Cmd.ExecuteScalar();
How to perform Database operations in MVC?
It will be same like we did above.
-----------
What are the steps included to get a collection of records from database in C#?
May 27, 2014 at 7:07pm
1. First you need SQL connection string
String
connectionString="Server=ServerAddress;Database=myDataBase;UserId=my
Username; Password=myPassword;";
2. Create an object of SqlConnection class as follows.
SqlConnection connection = new SqlConnection(connectionString)
3. Create an object of SQLCommand class as follows and assign query and Connection to
it as follows.
SqlCommandcmd = new SqlCommand(“Select * from Employee” , connection);
4. Create and initialize SqlDataAdatper and pass command object to it.
SqlDataAdapter da = new SqlDataAdapter(cmd);
5. Create and initialize datatable object which will store your records set
DataTabledataTable=new DataTable();
6. Use the fill method of Adapter class to fire the query and store the resulset in the
datatable created in above step.
da.Fill(dataTable);
7. Now you can use this datable and bind it to grid or can do other things.
---------------
What is OOP? What are different properties provided by Object-oriented systems?
May 27, 2014 at 1:31pm
OOP is software designing technique where we think in terms of real world objects.
Different properties provided by Object-oriented systems: -
Following are characteristics of Object Oriented System’s:-
Abstraction
Abstraction
means show only what is necessary. Example color is abstracted to RGB.
By just making the combination of these three colors we can achieve any
color in world. So rather than remembering each and every color we just
use RGB.
Encapsulation
It is a process of hiding all the complex processing from the outside world and make’s your objects simple.
Inheritance
This concept helps to define parent child relationship between classes.
Polymorphism
It’s
a property of object to act differently under different conditions. For
instance a simple user object depending on conditions can act like a
admin or like data entry object.
Remember the word APIE (Abstraction, Polymorphism, Inheritance and Encapsulation).
-----------------
What is Native Image Generator (Ngen.exe)? Does NGEN.EXE always improve performance?
NGEN
stores full compiled.NET native code in to cache. In other words rather
than dynamically compiling the code on run time a full image of native
compiled code is stored in cache while installing the application. This
leads to better performance as the assembly loads and execute faster.
In
order to install full compiled native code in cache we can execute the
below command line from your visual studio command prompt.
ngen.exe install <assemblyname>
NGEN.EXE on improving performance: -
No,
it’s not always necessary that ngen.exe produces optimized code because
it uses the current environments parameters which can change over a
period of time. For instance a code compiled in windows XP environment
will not be the optimized code to run under windows 2008 server. So we
need to once test with ‘NGEN’ and without ‘NGEN’ to conclude if really
the performance increases.
--------------
What is the difference between arraylist and list? Are Arraylist faster or Arrays?
May 26, 2014 at 10:45am
Difference between arraylist and list: -
- Arrays are fixed in size while Arraylist is resizable.
- Arrays are strongly typed, in other words when you create an array it can store only one data type data. Arraylist can store any datatype.
Are Arraylist faster or Arrays: -
Array
list takes any data type which leads to boxing and unboxing. As arrays
are strongly typed they do not do boxing and unboxing. So arrays are
faster as compared to array list.
// Array definition
int[] str = new int[10];
// Array list definition
ArrayList MyList = new ArrayList();
Generic equivalent for array list, stack, queues and hashtable: -
Below are the listed generic equivalents for each of them:-
- Array list generic equivalent is List<int>.
- Stack generic equivalent is Stack<int>.
- Queue generic equivalent is Queue<int>.
- Hashtable generic equivalent is Dictionary<int,int>.
-------------------
What is the difference between shallow copying and deep copying with example?
This .NET interview questions will show difference between shallow copying and deep copying with example.
Shallow copying means just copy the structure whereas deep copying means copy structure and data both.
With an example: -
In .NET Datatable class have 2 methods: -
- Clone – Which will create and return new instance of datatable whose structure will match existing table’s structure. Structure means, Columns, type of columns, sequence of columns etc.
- Copy – Which will also copy the data inside current table.
------------------
Explain in details about Indexer and can we have static indexer in C#?
Many
time classes have contained (aggregated or composed) collections. For
example in the below code you can see we have a customer class which has
an address collection.

Now
let’s say we would like to like fetch the addresses collection by
“Pincode” and “PhoneNumber”. So the logical step would be that you would
go and create two overloaded functions one which fetches by using
“PhoneNumber” and the other by “PinCode”. You can see in the below code
we have two functions defined.

Now on the client side your code would look something as shown below.

Now
the above code is great but how about simplifying things further. In
more simplified as shown in the below code. In other words we want to
INDEXED the class itself.

You can see the below image where we can have two overloaded indexers “PinCode” and “PhoneNumber”.

This can be achieved by using an indexer. There are two things we need to remember about indexer:-
- “Indexer” is defined by using “this” keyword.
- “Indexer” is a property so we need to define set and get for the same.
Below is the code implementation for
indexer. You can see we have used “this” keyword with two overloaded
function one which will fetch us address by using the “phonenumber” and
the other by using “pincode”.

Once
you put the above “indexer” code you should be able to access the
address collection from the customer object using an indexer “[]” as
shown in the below figure.

Summarizing
in one sentence: - Indexers helps us to access contained collection
with in a class using a simplified interface. It’s a syntactic sugar.
Static indexer in C#:
No we cannot have Static indexer in C#.
---------------
How to create a windows service using .NET?
May 22, 2014 at 10:50am
This .NET interview questions which demonstrate to create windows services using .NET.
Windows
Services are long-running processes that runs at the background.It have
the ability to start automatically when the computer boots and also can
be manually paused, stopped or even restarted.
Following are the steps to create a service:-
Create a project of type “Windows Service”.

If you see, the class created it is automatically inheriting from “System.ServiceProcess.ServiceBase”.
You
can override the following events provided by service and write your
custom code. All the three main events can be used that is Start, stop
and continue.
protected override void OnStart(string[] args)
{
}
protected override void OnStop()
{
}
protected override void OnContinue()
{
}
Now to install the service you need to do run the install util exe.
InstallUtil <Project Path>\BIN\MyNewService.exe
-------------
Explain the difference between Icomparable and IComparer?
This .NET interview questions will show difference between Icomparable and IComparer asked by the interviewer.
“IComparable”
interface helps you to implement a default sort implementation for the
collection. But what if we want to sort using multiple criteria’s?.For
those instances “IComparable” has a limitation and “IComparer” is the
guy.
For
example if we want to sort the list by “Name” under some situation or
sort by “Age” under some other situations we need to implement
“IComparer” interface.
So
the first step is to create different classes for each sort criteria.
These classes will implement “IComparer” interface and will have sorting
logic defined in the “Compare” method. You can see we have two
different classes defined “CompareByName” and “CompareByAge”. One
compares on the basis of “name” and the other on the basis of “age”.
class CompareByName : IComparer<Person>
{
public int Compare(Person x, Person y)
{
return string.Compare(x.Name, y.Name);
}
}
class CompareByAge : IComparer<Person>
{
public int Compare(Person x, Person y)
{
if (x.Age > y.Age) return 1;
if (x.Age < y.Age) return -1;
return 0;
}
}
If
you see the logic for “CompareByName” its simple. It uses the string
comparison to evaluate the “Name” value sorting. But when we talk about
numeric comparison there are 3 possible outputs Greater than , less than
or Equal. So if you see “CompareByAge” class it returns 3 values 1 (
Greater than) , -1 ( Less than ) and 0 ( for Equal to).
Now
that we have created the separate logics we can now invoke the
“Peoples’ list by passing the class object. So for example if we want to
sort by name, you will use the below code snippet.
Peoples.Sort(new CompareByName());
The output of the above code is nothing but alphabetically sorted data.
Ajay 20
Loki 40
Madan 20
Raju 20
Shiv 20
Sukesh 30
If you invoke the sort method of the list by using the age logic it will throw an output sorted on age value.
Peoples.Sort(new CompareByAge());
Ajay 20
Raju 20
Shiv 20
Madan 20
Sukesh 30
Loki 40
So
the difference is really default internal implementation or
customizable external implementation. When we use “IComparable” we can
have only one default sorting logic and that logic goes inside the
collection itself. For “IComparator” the logic is outside the collection
, in other words more extensible and the collection is not disturbed.

--------------
Explain ENUM and its benefits? What is the use of Flagsin ENUM?
ENUM
helps to define, manage and assign constants in effective way. Now the
below sample code is good but the level values are not readable.
if (level == 0){Console.WriteLine("Below quality");}
else if (level == 1){Console.WriteLine("Moderate quality");}
else if(level == 2){Console.WriteLine("High quality");}
Now by declaring a simple ENUM called as Quality as shown below.
enum Quality
{
Low = 0,
Moderate = 1,
High = 2
};
Our
code would look more readable as shown below. The other big benefit is
if we change the numeric values of quality we do not have to change
throughout the project. So we can go a change the Low quality to 1 and
no change in code is required.
if (level == Quality.Low){Console.WriteLine("Below quality");}
else if (level == Quality.Moderate){Console.WriteLine("Moderate quality");}
else if(level == Quality.High){Console.WriteLine("High quality");}
So summarizing ENUM has two big benefits:-
- Code becomes more readable.
- Easy to change constants without affecting throughout the project. Easy maintenance.
Uses of Flagsin ENUM:
“Flags” is an ENUM attribute. If you want to set multiple values to an ENUM we need to use Flags.
[Flags]
enum MyColors
{
Green = 0,
Red = 1,
Blue = 2
};
In the below code we are setting “MyColors” ENUM to “Blue” and “Green” value.
MyColors color = MyColors.Blue | MyColors.Green;
if ((color & MyColors.Blue) == MyColors.Blue)
{
Console.WriteLine(" Blue");
}
if ((color & MyColors.Green) == MyColors.Green)
{
Console.WriteLine(" Green");
}
What is an IL code? Why IL code is not fully compiled? Is it possible to view the IL code?
It
is a CPU independent partially compiled code. Partial/half compiled
means this code is not yet compiled to machine/CPU specific
instructions.
IL code compilation:
We
do not know in what kind of environment.NET code will run. In other
words we do not know what can be the end operating system, CPU
configuration, machine configuration, security configuration etc. So the
IL code is half compiled and on runtime this code is compiled to
machine specific using the environmental properties (CPU, OS, machine
configuration etc).
Viewing IL code:
Yes
by using ILDASM simple tool we can view a IL code of a DLL or EXE. In
order to view IL code using ILDASM, go to visual studio command prompt
and run “ILDASM.EXE”. Once ILDASM is running you view the IL code.
------------
Explain managed and unmanaged code and how to clean it?
May 17, 2014 at 5:48pm
Code that executes under CLR execution environment is called as managed code.
Unmanaged code executes
outside CLR boundary. Unmanaged code is nothing but code written in
C++, VB6, VC++ etc. Unmanaged codes have their own environment in which
the code runs and it’s completely outside the control of CLR.
Cleaning managed and unmanaged code:-
Garbage collector only claims managed code memory.
Garbage collector is a feature of CLR which cleans unused managed (it
does not clean unmanaged objects) objects and reclaims memory. It’s a
back ground thread which runs continuously and at specific intervals it
checks if there are any unused objects whose memory can be claimed.
For unmanaged code you need to put clean up in destructor/finalize. Finalize is a destructor and dispose is a function which is implemented via ‘Idisposable’ interface.
Finalize
is nondeterministic, since it’s called by garbage collector. Dispose is
a function and needs to be called by the client for clean up. In other
finalize is automatically called by garbage collector while dispose
needs to be called forcefully.
------------
What is stack/heap and Value types/Reference types?
May 16, 2014 at 12:29pm
This is basic .NET interview questions asked by the interviewer.
Stack
and heap are memory types in an application. Stack memory stores data
types like int , double , Boolean etc. While heap stores data types like
string and objects.
For
instance when the below code run the first two variables i.e. “i” and
“y” are stored in a stack and the last variable “o” is stored in heap.
void MyFunction()
{
int i = 1; // This is stored in stack.
int y = i; // This is stored in stack.
object o = null; // This is stored in heap.
}
// after this end the stack variable memory space is reclaimed while
// the heap memory is reclaimed later by garbage collector.
Value types and Reference types: -
Value types contain actual data while reference types contain pointers and the pointers point to the actual data.
Value
types are stored on stack while reference types are stored on heap.
Value types are your normal data types like int, bool, double and
reference types are all objects.
-----------------
What steps will you take to test application performance?
Scenario
based .NET interview questions is mostly asked by the interviewer. Here
we have put one scenario which was asked during an interview.
Suppose
that we have a website which is already developed and we are about to
go live onto server. After installation we realized that application
performance is not up to the mark then what will you do?
Step 1: - First I will confirm whether HTTP Compression is enabled or not in IIS. If not I will enable it.
Step 2: - With
the help of some tools like CLR profiler I will make sure that objects
are properly releasing from memory once it become unusable.
Step 3: - If that wont worked out I will move to indexes in SQL. I will check whether I indexes are properly created or nothing.
Step 4: - If
that won’t help out I will get into application source code and check
for static variables and try to minimize it. I will also try to find the
session management techniques and session variables and try to minimize
it as well.
Step 5: - Finally
if nothing of above worked out I will get into root of the code and try
optimizing logic. Example replace string with stringbuilder, Remove
unnecessary iteration loops etc.
------------
Explain Cohesion and coupling ( .NET and C# Architecture level interview question) ?
May 15, 2014 at 11:55am
Recently
there was a .NET architect position interview in polaris and this
question was asked to almost all candidates. Lot of people were aware of
coupling but not of cohesion. So below goes a full explanation in
detail with examples.
If you look at the dictionary meaning of cohesion it means sticking things together which are of the same types or substance.
Cohesion in software is a measure which tells how strongly related the responsibilities of a class or module is.
For
example below is a class diagram of a simple “customer” class. In
this class diagram “CustomerName” and “CustomerCode” are very much
related to the “Customer” class but watch the “SupplierCode” property
it’s not related directly.
Because this class has unrelated elements it has LOW.

Cohesion
can be at any level class level, module level etc. For example below is
a simple package diagram which groups classes in a “Customer” package.
Now
Customers buy products and have multiple addresses. So it’s logical to
have “Customer” , “Product” and “Address” in this namespace but look at
“Exception” and “Logger” classes they are needed but they are not
logically the part of “Customer” namespace.

So below grouping would look more logical and appropriate.

Coupling
is a contrast to cohesion. Coupling says how much the classes and
modules directly depend on each other. A good architecture is that
architecture where change in one place should not lead to changes all
over the places. If classes are directly connected with each other, then
change in one class leads to changes in other class as well , so a
loose coupling is more desirable.
Below
is a simple class diagram which shows “Customer” and “Address”
relationship. In the first section of the diagram “Customer” and
“Address” classes are directly connected. In other words changes in
“Address” class will lead to change in “Customer” class as well. So
rather than these classes talk with each other directly they can talk
via interfaces which the next section of the diagram shows. This is
termed as decoupling.

Coupling
and cohesion are measured using ordinal measurement: - LOW and HIGH. So
we have low cohesion , high cohesion , low coupling and high coupling.
Below table explains the same in detail.

In other words, good software architectures have high cohesion and low coupling.
---------------
6 important C# Delegate interview questions and answers
May 13, 2014 at 2:32pm
What is a delegate?
Delegate
is a safe pointer to a method / function. So rather than pointing to
the actual function you point to a delegate and via this delegate you
can invoke the methods / functions.
What is a point of a pointer when we can invoke the actual function/method?
Many
times rather than pointing to actual methods , we would like to point
to abstraction. For example rather than pointing to “Add(int,int)” ,
“Substract(int,int)” , we create an abstract delegate pointer
“Operation(int,int)” and point to any of them above.
What are the uses of delegates ?
There are two basic uses of delegates :-
- Callbacks / events.
- Method and function abstraction.
What are events ?
Events are encapsulation over delegates.
What are multi-cast delegates ?
If we want one delegate to point to multiple methods / function we use multicast delegates.
What are the different ways of creating a delegate in C# ?
- Action
- Func
- Predicate
- Lambda
- Anonymous types
--------------------
How to maintain performance and can clean unmanaged objects?
May 13, 2014 at 11:35am
We need to follow the below steps:-
- Implement IDisposable interface and implement the dispose function.
- In Dispose function calls the “GC.SuppressFinalize” method.
- At the client side ensure that the “Dispose” function is called when the object is no more required.
Below goes the code, this is also
called as “Finalize and Dispose pattern”. This ensures that your objects
are created in Generation 0 rather than Generation 1.
“GC.SuppressFinalize” tells the garbage collector to not worry about
destructor and destroy the objects in the first call itself.
class clsMyClass : IDisposable
{
~clsMyClass()
{
// In case the client forgets to call
// Dispose , destructor will be invoked for
Dispose(false);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// Free managed objects.
}
// Free unmanaged objects
}
public void Dispose()
{
Dispose(true);
// Ensure that the destructor is not called
GC.SuppressFinalize(this);
}
}
-------------------
What benefits does sealed keyword provide?
In
.NET “sealed” keyword helps to stop class from further inheriting by
using the "Sealed" keyword. For instance below is a simple sample code
where we have a class called as "Human" which is further inherited to
create a "Male" or "Female" class.
Now
the below code is great but we do not anyone to further inherit from
"Male" or "Female" class. In simple words "Male" and "Female" are the
last legs in this inheritance hierarchy. This can be done by using the
"Sealed" keyword.
public class Human
{}
public sealed class Male : Human
{}
public sealed class Female : Human
{}
If anyone tries to inherit the sealed classes he will end with the below error "cannot derive from sealed type".
------------------
How can we improve performance of .NET/ASP.NET/SQL Server?
May 10, 2014 at 5:08pm
This question is asked especially senior candidates and sometimes to juniors also. You can have various other forms like
- How can we improve performance of ASP.NET,
- How can we improve performance of SQL Server etc.
Remember 5 best points of each
category. You can pick your favorite ones. But whatever you pick should
be commonly used by everyone.
Below
are some common points you can remember. List is endless but I do not
want to make it long, so that you can remember important ones.
- Use string builder for concatenation rather than string when concatenation huge string values.
- Avoid boxing/unboxing, use generics.
- Avoid writing in line SQL queries use stored procedures.
- Choose your indexes (clustered and non-clustered) properly.
- Use Caching for data which will not change frequently.
- In ASP.NET use output cache directive for page level caching.
--------------------
Gridview Textbox value - How will you get the value of textbox on button click?
May 9, 2014 at 3:27pm
Interview
is not about theory and fundamentals. Interviewer asks practical
questions as well to check developer’s practical knowledge. So here we
have a practical oriented ASP.NET interview questions raised scenario
based.
Interviewer - Let
say we have a ASP.NET grid view containing a button and a textbox in
every row. How will you get the value of textbox on button click.
Correct Answer -
1. Will set CommandName for button. Let say as "EditRow"
2. We will use Gridview row commamd event
3. In event handler function we will be having a parameter as "GridViewaCommandArguments e"
This
row command even will be fired everytime we click any button in the
gridview, thats why, First we have to confirm that even is coming
because of correct control. For that we will use CommandName property of
GridViewaCommandArguments class and compare it with the value we set,
that is "EditRow". In short we will write a "If" condition.
4. Finally we will use following syntaxt and get the value of textbox.
Textbox t =e.Row.FindControl("MyTextboxId") as Textbox;
string value=t.Text;
Note: e indicates GridViewaCommandArguments and MyTextboxId is simply the Id of textbox in the gridview.
----------------
What is shadowing? What is the difference between Shadowing and Overriding?
May 9, 2014 at 11:19am
Shadowing: -
Shadowing
replaces the complete element of the parent class. For instance you can
see in the below sample code where the clsParent has a variable int
“i”, which is replaced by the child class clsChild by a method “i”.
In other words when you refer the parent object “i” it is a variable and when you refer the child object“i” it is a method.
class clsParent
{
public int i=0;
}
class clsChild : clsParent
{
public new void i()
{
Console.WriteLine("Hey i became a method");
}
}
Difference between Shadowing and Overriding: -
Overriding redefines only the implementation while shadowing redefines the whole element.
---------------
How is ASP.NET page life cycle executed and ASP.NET application life cycle works?
May 8, 2014 at 8:03pm
Execution of ASP.NET page life cycle: -
For quick reference always remember the word SILVER: - SI ( Init ) L ( Load) V ( Validate) E ( Event ) R ( Render) .
And following is the sequence in which the events occur:-
- Init
- Load
- Validate
- Event
- Render
Working of an ASP.NET application life cycle: -
Note
:- When any one asks for page life the SILVER answer is appropriate ,
but when interviewer is asking for application life cycle , two more
things come in to picture handlers and modules.
Below is how ASP.NET events fire.
- First the HttpModule events like BeginRequest , AuthenticateRequest fires.
- Then the HttpHandlers fires if the file extension match of the request page name.
- Finally Page events fire i.e. init, load, validate, event and render.
-----------------
How to implement practically Lazy loading in .NET?
May 6, 2014 at 4:02pm
In
.NET we have “Lazy<T>” class which provides automatic support for
lazy loading. So let’s say if you want to implement “Lazy<>” in
the above code we need to implement two steps for the same:-
Create the object of orders using the “Lazy” generic class.
private Lazy<list> _Orders= null;</list>
Attach this Lazy<> object with the method which will help us load the order’s data.
_Orders = new Lazy<list>(() => LoadOrders());</list>
Now as soon as any client makes a call to the “_Orders” object, It will call the “LoadOrders” function to load the data.
You will get the “List<Orders>” data in the “Value” property.
public List<Order> Orders
{
get
{
return _Orders.Value;
}
}
Below goes the full code for the same.
public class Customer
{
private Lazy<list> _Orders= null;</list>
public List<Order> Orders
{
get
{
return _Orders.Value;
}
}
public Customer()
{
// Makes a database trip
_CustomerName = "Shiv";
_Orders = new Lazy<list>(() => LoadOrders());</list>
}
}
--------------
Interface vs. abstract class
May 5, 2014 at 5:32pm
Very
first Technical answer for this will be, Interface contains only method
declaration whereas abstract class may contain method definition as
well.
In real life how will you identify whether we should choose interface or abstract class.
Interfaces,
- Make our code loosely coupled.
- Creates a contract or rule which all derived classes should follow.
- Let us defined the structure of our class.
Abstract classes,
- Make our code loosely coupled.
- Creates a contract or rule which all derived classes should follow.
- Let us define the structure and may be the flow sometimes.
public abstract class MyAbstractClass
{
public void Process()
{
//Some Opertations
step1();
step2();
//Some Opertations
}
public abstract step1();
public abstract step2();
}
Every
class which inherits above class must define step1 and step2 and so we
can say structure of our class is predefined. When the end developer
invoke the process function it will always execute the step1 first and
then step2. It means, flow is also pre-defined.
So in simple words, when you use abstract class you can also have methods with body.
So why don’t we always use abstract class?
Because
when we use abstract class we get bound to single inheritance. Class
which inherits from abstract class cannot inherit from another class.
This is not the case with interfaces. We can also have multiple
inheritance with inheritance.
-----------------
Can we have multiple ScriptManager control on a single page ? ( ASP.NET Ajax Interview questions)
No,
we cannot have a multiple script manager control on a single page.
Single script manager control can have multiple update panels to define
partial sections of the page.
------------
What is a Garbage Collector? What is GAC(Global Assembly Cache)?
Garbage
collector is a feature of CLR which cleans unused managed (it does not
clean unmanaged objects) objects and reclaims memory. It’s a back ground
thread which runs continuously and at specific intervals it checks if
there are any unused objects whose memory can be claimed.
What is GAC?
GAC (Global Assembly Cache) is where all shared .NET assembly resides. GAC is used in the following situations:-
- If assemblies have to be shared among several application, which reside in the same computer.
- If the assembly has some special security, requirements like only administrators can remove the assembly. If the assembly is private then a simple delete of assembly the assembly file will remove the assembly.
----------------
IEnumerable vs IQueryable ? ( .NET Interview question)
April 28, 2014 at 12:43pm
Both
these interfaces are for .NET collection’s so if you are new to .NET
collection please first see this video before reading the article :- https://www.youtube.com/watch?v=hDykzD-3z8k
The
first important point to remember is “IQueryable” interface inherits
from “IEnumerable”, so whatever “IEnumerable” can do, “IQueryable” can
also do.

There
are many differences but let us discuss about the one big difference
which makes the biggest difference. “IQueryable” interface is useful
when your collection is loaded using LINQ or Entity framework and you
want to apply filter on the collection.
Consider
the below simple code which uses “IEnumerable” with entity framework.
It’s using a “where” filter to get records whose “EmpId” is “2”.
EmpEntities ent = new EmpEntities();
IEnumerable<Employee> emp = ent.Employees;
IEnumerable<Employee> temp = emp.Where(x => x.Empid == 2).ToList<Employee>();
This
where filter is executed on the client side where the “IEnumerable”
code is. In other words all the data is fetched from the database and
then at the client its scans and gets the record with “EmpId” is “2”.

But now see the below code we have changed “IEnumerable” to “IQueryable”.
EmpEntities ent = new EmpEntities();
IQueryable<Employee> emp = ent.Employees;
IQueryable<Employee> temp = emp.Where(x => x.Empid == 2).ToList<Employee>();
In
this case the filter is applied on the database using the “SQL” query.
So the client sends a request and on the server side a select query is
fired on the database and only necessary data is returned.

So
the difference between “IQueryable” and “IEnumerable” is about where
the filter logic is executed. One executes on the client side and the
other executes on the database.
So
if you working with only in-memory data collection “IEnumerable” is a
good choice but if you want to query data collection which is connected
with database “IQueryable” is a better choice as it reduces network
traffic and uses the power of SQL language.
In
similar lines many times in .NET interviewsinterviewers tell to compare
“IEnumerable” vs “IEnumerator”. Below is a nice video which answers
and demonstrates the difference between “IEnumerable” vs “IEnumerator”.
--------------
What is the best practice to update interface with new methods?
Practical
scenario based .NET interview questions asked by interviewer on OOPS
interface. So following is the practical explanation to it.
One liner answer: -
During interview one single simple sentence to answer it.
Interface
once fixed should not be changed. If we ever have to add new functions,
new interfaces should be created so that we do not break compatibility
with old clients.
Explanation: -
The
biggest use of interface is to ensure that strict CONTRACT is followed
between clients and components. So that when changes happen on the
components clients do not have to change too much. In real world
CONTRACTS between two parties do not change which implies that
interfaces should also not change.
So
if you want to add new methods or change methods in interfaces the best
practice is to create new interfaces by inheriting. With this approach
your older client who are using the interface stay happy and the new
clients who want those new or changed methods get the benefits of the
new functionality.
Let’s
consider you have a simple interface called as “IView” which helps you
to view data , below is the code for the same. Let’s consider that this
interface is consumed by many clients.
interface Iview
{
public void View();
}
Over
a period of time some users demand “Edit” functionality as well but the
rest of the users are happy with the ‘View” functionality and they do
not want them to get affected by these changes. Now if you go and change
this interface ( “IView”) a.k.a you will be disturbing everyone.

So
the best option would be to add a new interface i.e. “IEdit” which
inherits from “IView”. So the “IEdit” will have the functionality for
“Edit” as well as “View” because it’s also inheriting from “IView”. And
the clients who are consuming “IView” do not need to update as “IView’
is not changed at all.
interface IEdit : Iview
{
public void Edit();
}
-----------
What is JIT ( Just in time)?
IL
code is a half compiled code during runtime this half compiled code is
compiled in to full machine language. This compilation is done by JIT.
What are different types of JIT ?
Normal-JIT (Default): - This the methods needed during runtime and caches them.
Econo-JIT: - This compiles the methods needed during runtime but there is no caching.
Pre-JIT:
- This compiles the complete source code into native code during build
itself. No compilation happens during runtime , there is no activity
from JIT during runtime. We can implement Pre-jit by using ngen.exe.
Explain NGEN.EXE ?
Ngen
stores full compiled.NET native code in to cache. In other words rather
than dynamically compiling the code on run time a full image of native
compiled code is stored in cache while installing the application. This
leads to better performance as the assembly loads and execute faster.
In
order to install full compiled native code in cache we can execute the
below command line from your visual studio command prompt.
ngen.exe install <assemblyname>
No comments:
Post a Comment