0% found this document useful (0 votes)
9 views

CSharp-Dotnetfunda

The document provides an overview of various C# concepts, including the use of Monitor for synchronizing access to objects, looping through DataTable rows, and the purpose of lock statements. It also covers topics such as static constructors, reflection, delegates, collections, and the differences between classes and structures. Additionally, it discusses error types, garbage collection, application domains, and the nuances of shared assemblies and data handling in C#.

Uploaded by

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

CSharp-Dotnetfunda

The document provides an overview of various C# concepts, including the use of Monitor for synchronizing access to objects, looping through DataTable rows, and the purpose of lock statements. It also covers topics such as static constructors, reflection, delegates, collections, and the differences between classes and structures. Additionally, it discusses error types, garbage collection, application domains, and the nuances of shared assemblies and data handling in C#.

Uploaded by

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

CSHARP From www.dotnetfunda.

com

What is the use of Monitor in C#?

It provides a mechanism that synchronizes access to objects.


The Monitor class controls access to objects by granting a lock for an object to a single
thread. Object locks provide the ability to restrict access to a block of code, commonly
called a critical section. While a thread owns the lock for an object, no other thread can
acquire that lock. You can also use Monitor to ensure that no other thread is allowed to
access a section of application code being executed by the lock owner, unless the other
thread is executing the code using a different locked object.
For more visit http://msdn2.microsoft.com/en-us/library/system.threading.monitor.aspx

How to loop through all rows of the DataTable?

You can do this in more than one way but ForEach loop is much better than any other
way in terms of cleanliness of the code or performance.

ForEach loop
foreach (DataRow row in dTable.Rows)
{
yourvariable = row["ColumnName"].ToString();
}

For loop
for (int j = 0; j< dTable.Rows.Count; j++)
{
yourvariable = dTable.Rows[j]["ColumnName"].ToString()l
}

What is lock statement in C#?

Lock ensures that one thread does not enter a critical section of code while another
thread is in the critical section. If another thread attempts to enter a locked code, it will
wait, block, until the object is released.

Is overriding of a function possible in the same class?

NOTE: This is objective type question, Please click question title for correct
answer.

What is static constructor?


Static constructor is used to initialize static data members as soon as the class is
referenced first time, whereas an instance constructor is used to create an instance of that
class with keyword. A static constructor does not take access modifiers or have
parameters and can't access any non-static data member of a class.

What is reflection?

Reflection is the ability to find the information about types contained in an assembly at
runtime.
OR
Reflection is the ability to find out information about objects, the application details
(assemblies), its metadata at run-time.
Edited: See the example: http://www.dotnetfunda.com/articles/article132.aspx

What is Delegates?

A delegate in C# allows you to pass method of one class to objects of other class that can
call these methods.
OR
A delegate is an object that holds the reference to a method.
In C++ it is called function pointer.

What is SortedList?

This is a collection and it is a combination of key/value entries and an ArrayList


collection. Where the collection is sorted by key.

What is BitArray?

The BitArray collection is a composite of bit values. It stores 1 or 0 where 1 is true and 0
is false. This collection provides an efficient means of storing and retrieving bit values.

What is HashTable?
A Hashtable is a collection of key-value pairs. Entries in this are instance of
DictionaryEntry type. It implements IDictionary, ISerilizable, IDeserializable collback
interface.

Are private class-level variables inherited?

Yes, but they are not accessible. Although they are not visible or accessible via the class
interface, they are inherited.
How is the DLL Hell problem solved in .NET?

Assembly versioning allows the application to specify not only the library it needs to run
(which was available under Win32), but also the version of the assembly.

What is a collection?
A collection serves as a container for instances of other classes. All classes implement
ICollection interface which intern implement IEnumerable interface.

What is Stack?

This is a collection that abstracts LIFO (Last In First Out) data structure in which initial
capacity is 32.

What is Queue?

This is a collection that abstracts FIFO (First In First Out) data structure. The initial
capacity is 32 elements. It is ideal for messaging components.

What is an ArrayList?

ArrayList is a dynamic array. Elements can be added & removed from an arraylist at the
runtime. In this elements are not automatically sorted.

What is an Array?

An array is a collection of related instance either value or reference types. Array posses
an immutable structure in which the number of dimensions and size of the array are fixed
at instantiation.

C# Supports Single, Mult dimensional and Jagged Array.

Single Dimensional Array: it is sometimes called vector array consists of single row.
Multi-Dimensional Array: are rectangular & consists of rows and columns.
Jagged Array: also consists of rows & columns but in irregular shaped (like row 1 has 3
column and row 2 has 5 column)
How to load assembly from GAC?

Lets say you have to load the assembly from GAC on button click event then you should
write following method.
protected void btn_Click(object sender, EventArgs e)
{
AssemblyName asm = new AssemblyName("ClassLibrary1,
Version=1.1.0.0, Culture=neutral, PublicKeyToken=fbc28d9ca2fc8db5");
Assembly al = Assembly.Load(asm);
Type t = al.GetType("ClassLibrary1.Class1");
MethodInfo m = t.GetMethod("Method1");
str = "reflection - " + (string)m.Invoke(null, null);
MessageBox.Show(str);
}
For more visit
http://www.infosysblogs.com/microsoft/2007/04/loading_multiple_versions_of_s.html

How to declare a property in a class?

int m_PersonID = 0;
public int PersonID
{
get { return m_PersonID; }
set { m_PersonID = value; }
}

How to declare a property in an Interface?

DateTime DateOfBirth { get;set;}


int Age { get;set;}
string FirstName { get;set;}
As this is an Interface, so no implementation required only definition of properties are
required. Implementation of these properties will be written into the class inherting this
interface.

Difference Between dispose and finalize method?

Dispose is a method for release from the memory for an object.


For eg:
<object>.Dispose.
Finalize is used to fire when the object is going to release the memory.We can set a alert
message to says that this object is going to dispose.

How to declare methods into an Interface


void Calculate();
int Insert(string firstName, string lastName, int age);
Interface doesn't contain implementation so methods implementation will be written into
class inherting this interface.

What is the use of CommandBehavior.CloseConnection?

We can use pass it with ExecuteReader method of Command object like


reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
This will make sure that when we are calling reader.Close() the associated connection
object will also be closed.

What are the different ways a method can be overloaded?

Different parameter data types, different number of parameters, different order of


parameters.

Can you allow a class to be inherited, but prevent the method from being over-ridden?
Yes. Just leave the class public and make the method sealed.

Can you prevent your class from being inherited by another class?
Yes. The keyword “sealed” will prevent the class from being inherited.

What class is underneath the SortedList class?

A sorted HashTable.

How can you sort the elements of the array in descending order?

By calling Array.Sort() and then Array.Reverse() methods.

What’s the difference between the System.Array.CopyTo() and


System.Array.Clone()?

The Clone() method returns a new array (a shallow copy) object containing all the
elements in the original array. The CopyTo() method copies the elements into another
existing array. Both perform a shallow copy. A shallow copy means the contents (each
array element) contains references to the same object as the elements in the original
array. A deep copy (which neither of these methods performs) would create a new
instance of each element's object, resulting in a different, yet identacle object.
Write a single line of code to create a text file and write contents into it.

System.IO.File.WriteAllText(@"c:\MyTextFile.txt", "MyContents");

Write a single line of code to read the entire content of the text file.

string strContent = System.IO.File.ReadAllText(Server.MapPath("~/MyTextFile.txt"));

How to read entire stream contents?


If you have a stream object (any of the stream like StreamReader, MemoryStream,
FileStream) and you want to show its content, write following code.

// here theStream is the stream object

while (myStream.Position != myStream.Length)


{
Console.WriteLine("{0:x2}", myStream.ReadByte());
}

How to sort an array into descending order?


First sort the array using Array.Sort and then use Array.Reverse
int[] number = new int[] {6, 4, 7};
Array.Sort(number); // sort in ascending order
foreach (int i in number)
{
lblMessage.Text += i + " <br />";
}
// reverse ie descending order
Array.Reverse(number);
lblMessage.Text += "<hr />";
foreach (int i in number)
{
lblMessage.Text += i + " <br />";
}
How to convert a sentence into Title Case (Capitalize first character of every word)?
Use ToTitleCase method.
System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(&qu
ot;dotnetfunda.com is a very good website&quot;);

The output will be "Dotnetfunda.Com Is A Very Good Website"

Difference between classes and structures?

A struct is a value type and a class is a reference type.


When we instantiate a class, memory will be allocated on the heap and when struct gets
initiated it gets memory on the stack.
Classes can have explicit parameter less constructors. But structs dosn't have this.
Classes support inheritance. No inheritance for structs.
A struct cannot inherit from another struct or class, and it cannot be the base of a class.
Like classes, structures can implement interfaces.

Types of Errors ?
Configuration Errors
Parser Errors
Compilation Errors
Run-Time Errors

What happens if you inherit multiple interfaces and they have conflicting method
names?

It’s up to you to implement the method inside your own class, so implementation is left
entirely up to you. This might cause a problem on a higher-level scale if similarly named
methods from different interfaces expect different data, but as far as compiler cares
you’re okay.

What class is underneath the SortedList class?

A sorted HashTable

Are private class-level variables inherited?


Yes, but they are not accessible. Although they are not visible or accessible via the class
interface, they are inherited.

What’s the difference between System.String and System.Text.StringBuilder


classes?

System.String is immutable. System.StringBuilder was designed with the purpose of


having a mutable string where a variety of operations can be performed.

What does the term immutable mean?

The data value may not be changed. Note: The variable value may be changed, but the
original immutable data value was discarded and a new data value was created in
memory.
What is the best way to add items from an Array into ArrayList?

Use AddRange method of the ArrayList.


string[] arr = new string[] { "ram", "shyam", "mohan" };
ArrayList arrList = new ArrayList();
arrList.AddRange(arr);

What is Attribute Programming? What are attributes? Where are they used?

Attributes are a mechanism for adding metadata, such as compiler instructions and other
data about your data, methods, and classes, to the program itself. Attributes are inserted
into the metadata and are visible through ILDasm and other metadata-reading tools.
Attributes can be used to identify or use the data at runtime execution using .NET
Reflection.

Is String is Value Type or Reference Type in C#?

String is an object (Reference Type).

What is extension method in C#?

Extension method is a new feature in C# 3.0.

Extension methods allow existing classes to be extended without relying on inheritance


or having to change the class's source code. This means that if you want to add some
methods into the existing String class you can do it quite easily.

Here's a couple of rules to consider when deciding on whether or not to use extension
methods:

* Extension methods cannot be used to override existing methods


* An extension method with the same name and signature as an instance method will not
be called
* The concept of extension methods cannot be applied to fields, properties or events
* Use extension methods sparingly....overuse can be a bad thing!

For more details, see http://weblogs.asp.net/dwahlin/archive/2008/01/25/c-3-0-features-


extension-methods.aspx

What is partial class?


Partial class is a new functionality added in since .NET Framework 2.0 version. It allows
to split us to split the definition of one class, struct, interface into multiple source files.
Each source file contains a section of definition, and all parts are combined when the
application is compiled.

For more detail see http://msdn.microsoft.com/en-us/library/wa80x488(VS.80).aspx

What is nested class?

A Nested classes are classes within classes.

OR

A nested class is any class whose declaration occurs within the body of another class or
interface.

For more details see http://www.codeproject.com/KB/cs/nested_csclasses.aspx

What is top-level class?

A top level class is a class that is not a nested class.

See what is nested class http://www.dotnetfunda.com/interview/exam281-what-is-nested-


class.aspx

What is garbage collection?


Garbage collection is a mechanism that allows the computer to detect when an object can
no longer be accessed. It then automatically releases the memory used by that object (as
well as calling a clean-up routine, called a "finalizer," which is written by the user). Some
garbage collectors, like the one used by .NET, compact memory and therefore decrease
your program's working set.

What is an application domain?


An application domain (often AppDomain) is a virtual process that serves to isolate an
application. All objects created within the same application scope (in other words,
anywhere along the sequence of object activations beginning with the application entry
point) are created within the same application domain. Multiple application domains can
exist in a single operating system process, making them a lightweight means of
application isolation.

An OS process provides isolation by having a distinct memory address space. While this
is effective, it is also expensive, and does not scale to the numbers required for large web
servers. The Common Language Runtime, on the other hand, enforces application
isolation by managing the memory use of code running within the application domain.
This ensures that it does not access memory outside the boundaries of the domain. It is
important to note that only type-safe code can be managed in this way (the runtime
cannot guarantee isolation when unsafe code is loaded in an application domain).

If I want to build a shared assembly, does that require the overhead of signing and
managing key pairs?

Building a shared assembly does involve working with cryptographic keys. Only the
public key is strictly needed when the assembly is being built. Compilers targeting
the .NET Framework provide command line options (or use custom attributes) for
supplying the public key when building the assembly. It is common to keep a copy of a
common public key in a source database and point build scripts to this key. Before the
assembly is shipped, the assembly must be fully signed with the corresponding private
key. This is done using an SDK tool called SN.exe (Strong Name).
Strong name signing does not involve certificates like Authenticode does. There are no
third party organizations involved, no fees to pay, and no certificate chains. In addition,
the overhead for verifying a strong name is much less than it is for Authenticode.
However, strong names do not make any statements about trusting a particular publisher.
Strong names allow you to ensure that the contents of a given assembly haven't been
tampered with, and that the assembly loaded on your behalf at run time comes from the
same publisher as the one you developed against. But it makes no statement about
whether you can trust the identity of that publisher.

What is the difference between Data Reader & Dataset?


Data Reader is connected, read only forward only record set.
Dataset is in memory database that can store multiple tables, relations and constraints;
moreover dataset is disconnected and is not aware of the data source.

What’s a delegate?

A delegate object encapsulates a reference to a method.

When do you absolutely have to declare a class as abstract?


1. When the class itself is inherited from an abstract class, but not all base abstract
methods have been overridden.
2. When at least one of the methods in the class is abstract.

What’s the advantage of using System.Text.StringBuilder over System.String?

StringBuilder is more efficient in cases where there is a large amount of string


manipulation. Strings are immutable, so each time a string is changed, a new instance in
memory is created.
what is Static?
Static:
1)A Static member data or a member function can be called without the help of an object.

2)Static members can be called with the help of Classname.

Syntax: classname.staticmember
3)'this ' keyword cannot be used inside a static member function
4)Nonstatic members cannot be used inside a static member function

Differrence between Array.CopyTo() and Array.Clone()

Posted by: Syedshakeer | Show/Hide Answer


Both CopyTo() and Clone() make shallow copy (data is copied) and used for Single
Dimension arrays.

Clone() method makes a clone of the original array. It returns an exact length array.

CopyTo() copies the elements from the original array to the destination array starting at
the specified destination array index. Note that, this adds elements to an already existing
array.

In VB.NET, variables has to be declared earlier, before using Clone or CopyTo methods
to store the values. The difference arise on mentioning the size of the array.

While declaring the varaiable that is used for CopyTo method, it should have the size
equal to or more than that of the original array.

While declaring the variable that is used for Clone method we need not mention the array
size. Eventhough the array size is small, it won't show any error, rather the array size gets
altered automatically on cloning. The cloned array size get created equal to the size of the
source array.

If value type is used for CopyTo/Clone any change in the values made on them will not
get reflected on the original whereas on reference type the change gets reflected.

Below is the code which would throw some light on your understanding.

Constructor and Destructor


Constructor:
-----------------

1. The Constructor is the first method that is run when an instance of a type is created. In
visual basic a constructor is always Sub new ().
2. Constructor are use to initialize class and structure data before use. Constructor never
returns a value and can be overridden to provide custom initialization functionality.

3. The constructor provides a way to set default values for data or perform other
necessary functions before the object available for use.

Destructor:
---------------
Destructors are called just before an object is destroyed and can be used to run clean-up
code. You can’t control when a destructor is called.

What is extension method in C#?

Posted by: SheoNarayan | Show/Hide Answer


This is a new feature in C# 3.0. This method allows us to add a new static method to the
existing classes.

For example, if we want to validate an Email address using the static method of the string
class (built-in) class, we can add an extension method like this.
public static bool IsValidEmail(this string input)

Regex regEx = new Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+


([-.]\w+)*");

return regEx.IsMatch(input);

Notice the parameter passed to above method. Here "this" indicates the string class. Now,
we can use above extension method like this.
string myEmail = "[email protected]";

bool IsValidEmailAddress = myEmail.IsValidEmail();

In this case as the format of the email id in myEmail variable is correct so


IsValidEmailAddress will be true.

What is anonymous type in C#?


This is a new feature in C# 3.0. This enable use to create a type/class on-the-fly at
compile time.

For example

var emp = new { Name = "Sheo", Gender = "Male", Active = true };

In this case a new type will be created on the fly that will have Name, Gender, and Active
as public property and its backing field like _Name, _Gender, _Active.

This is especially useful when we want to receive data from other object or iterate
through a collection and set values and do not want to create a class just to hold the data.
Note that anonymous types are just a placeholder, we can't customize its behavior or add
methods inside it.

What is the use of var keyword in C#?

This is the new feature in C# 3.0. This enable us to declare a variable whose type is
implicitly inferred from the expression used to initialize the variable.

var age = 10;

Because the initialization value (10) of the variable age is integer type of age will be
treated as integer type of variable. There are few limitation of the var type of variables.

They are:

#. They can't be initialized as null.


#. They need to be declared and initialized in the same statement.
#. They can't be used as a member of the class.

By default which class is inherited by a class in C#?


If no class is inhertited, by default a class inherit System.Object.

What is operator overloading in C#?

Operator overloading is a concept that enables us to redefine (do a special job) the
existing operators so that they can be used on user defined types like classes and structs.

For more information visit:


http://aspalliance.com/1227_Understanding_Operator_Overloading_in_C.all
What is operators in C# and how many types of operators are there in c#?

C# has a large set of operators, which are symbols that specify which operations to
perform in an expression.

Arithmetic
+-*/%

Logical (boolean and bitwise)


& | ^ ! ~ && || true false

String concatenation
+

Increment, decrement
++ --

Shift
<< >>

Relational
== != < > <= >=

Assignment
= += -= *= /= %= &= |= ^= <<= >>=

Member access
.

Indexing
[]

Cast
()

Conditional
?:

Delegate concatenation and removal


+-

Object creation
new

Type information
as is sizeof typeof
Overflow exception control
checked unchecked

Indirection and Address


* -> [] &

For more details visit http://msdn.microsoft.com/en-us/library/6a71f45d(VS.71).aspx

What is Partial Class?

Partial class

Instead of defining an entire class, you can split the definition into multiple classes by
using the partial keyword. When the application is complied, the C# complier will group
all the partial classes together and treat them as a single class. There are a couple of good
reasons to use partial classes. Programmers can work on different parts of a class without
needing to share the same physical file. Also you can separate your application business
logic from the designer-generated code.

C#
Public partial class Employee

public void DoWork()

{}

Public partial class Employee

public void GoToLunch()

{}

What is Global Assembly Cache?

Abbreviated as GAC, the Global Assembly Cache is a machine-wide store used to hold
assemblies that are intended to be shared by several applications on the machine. Each
computer where the common language runtime (CLR) is installed has a global assembly
cache. The global assembly cache stores the assemblies specifically designated to be
shared by several applications on the computer.

For more details visit


http://www.webopedia.com/TERM/G/Global_Assembly_Cache.htm

How to create a strong name?


To create a strong name key use following code
C:\>sn -k s.snk

Strong name key is used to specify the strong name used to deploy any application in the
GAC (Global Assembly Catch) in the system.

What is object pooling?

Object Pooling is something that tries to keep a pool of objects in memory to be re-used
later and hence it will reduce the load of object creation to a great extent.
Object Pool is nothing but a container of objects that are ready for use. Whenever there is
a request for a new object, the pool manager will take the request and it will be served by
allocating an object from the pool.
http://www.c-sharpcorner.com/UploadFile/vmsanthosh.chn/109042007094154AM/
1.aspx

What is the name of C# compiler?

The name of C# compiler is CSC.


eg. to create the executable of the .cs file you can use
csc File.cs

This will create File.exe file.

For more details visit: http://msdn.microsoft.com/en-us/library/78f4aasd.aspx

How and why to use Using statement in C#?

Using statement is used to work with an object in C# that inherits IDisposable interface.
IDisposable interface has one public method called Dispose that is used to dispose off the
object. When we use Using statement, we don't need to explicitly dispose the object in
the code, the using statement takes care of it. For eg.
Using (SqlConnection conn = new SqlConnection())
{}
When we use above block, internally the code is generated like this
SqlConnection conn = new SqlConnection()
try
{
}
finally
{
// calls the dispose method of the conn object
}
Using statement make the code more readable and compact.
For more details read http://www.codeproject.com/KB/cs/tinguusingstatement.aspx

can we declare a block as static in c#?


NO,because c# doesnot support static block,but it supports static method

What is a satellite assembly?


When you write a multilingual or multi-cultural application in .NET, and want to
distribute the core application separately from the localized modules, the localized
assemblies that modify the core application are called satellite assemblies.

What does assert() method do?


In debug compilation, assert takes in a Boolean condition as a parameter, and shows the
error dialog if the condition is false. The program proceeds without any interruption if the
condition is true.

What’s a multicast delegate?


A delegate that has multiple handlers assigned to it. Each assigned handler (method) is
called.

Difference between Static and ReadOnly?

Static: A variable that retains the same data throughout the execution of a program.
ReadOnly: you can’t change its value.

How can I programmatically list available queues?


The GetPublicQueuesByLabel , GetPublicQueuesByCategory , and
GetPublicQueuesByMachine methods of the MessageQueue class provide access to
queues on a network.To specify more exactly the type of queue you are looking for, the
GetPublicQueues method has a MessageQueueCriteria parameter in which you can
specify combinations of search criteria.

What is UDP and how does it work?

The User Datagram Protocol (UDP ) provides an unreliable datagram-oriented


protocol on top of IP.The delivery and order of datagrams are not guaranteed.
It is connection-less, that is, a UDP application does not have to connect
explicitly to another. Datagrams are simply sent or received.

How do I call a member method and pass a primitive type (Value Type) by
reference?

public bool GetValue( ref int returnValue );

This will pass the numeric by reference.You can modify the value of
returnValue within the body of GetValue and it will persist when the method
call returns.

How to write a method in a class and build as .dll

To generate a .dll you can following below steps

1. Right click your solution and select New Project.


2. Select Visual C# as Project type and Class Library as Templates (give proper name and
location path) and click OK.
3. Write some code in the class like below, you can add as many class you want.
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.IO;

namespace ClassLibrary1

public class Class1

public string GetMyName(string myName)

return myName;

}
4. Right click the Class Library project and select build.
5. Your .dll should be ready in the bin folder of the project location (either in the debug
or release folder) depends on which mode your project is.
6. To refer this .dll, you can right click your project and select Add References.
7. Select browse tab from the dialogue box and choose the .dll you have just generated.
8. Now to use the method of the class library in any code behind page or another class
library, you can use the namespace you had used in the class library (in above case
ClassLibrary1) like "using ClassLibrary1;"
9. Instantiate the class and use its method like below
Class1 c = new Class();

string myName = c.GetMyName("Poster");

How to declare a method in an Interface?


To declare method in an interface, you just need to write the definition of the method like
below.
void ProcessMyData(int id);

string GetMyName(int id);


There is no need of writing the modifier as by default all methods in the interface is
public.

How to explicitly implement the interface method?

To explicitly implement interface we need to prefix the method name with the name of
the interface following by .(dot).
string IInterface1.HelloNet()
{
return "Interface 1 : Hello NET";
}
Assuming that HelloNet method is in IInterface1 as well as another
interface that is inherited in the class.

What are the access-specifiers available in c#?

Private, Protected, Public, Internal, Protected Internal.

What are Sealed Classes in C#?

The sealed modifier is used to prevent derivation from a class. A compile-time error
occurs if a sealed class is specified as the base class of another class. (A sealed class
cannot also be an abstract class)
A try block having 4 catch block will fire all catch block or not?

No, A try having more than one catch block will fire the first relevant catch block after
that cursor will be moved to the finally block (if exists) leaving all remaining catch
blocks.
So in all cases only one catch block will fire.

What are three test cases you should do while unit testing?

Positive test cases


This is done with correct data to check for correct output)

Negative test cases


This is done with broken or missing data to check for proper handling

Exception test cases


This is done with exceptions (giving unexpected data or behavior) and check for the
exception caught properly or not.

What debugging tools come with the .NET Framework SDK?


CorDBG – command-line debugger
The Runtime Debugger helps tools vendors and application developers find and fix bugs
in programs that target the .NET Framework common language runtime. This tool uses
the runtime Debug API to provide debugging services. Developers can examine the code
to learn how to use the debugging services. Currently, you can only use Cordbg.exe to
debug managed code; there is no support for debugging unmanaged code. To use
CorDbg, you must compile the original C# file using the /debug switch.

Click for more details http://msdn.microsoft.com/en-us/library/a6zb7c8d(VS.80).aspx

DbgCLR – graphic debugger.

The Microsoft CLR Debugger (DbgCLR.exe) provides debugging services with a


graphical interface to help application developers find and fix bugs in programs that
target the common language runtime. The CLR Debugger, and the accompanying
documentation, is based on work being done for the Microsoft Visual Studio 2005
Debugger. As a result, the documentation refers mostly to the Visual Studio Debugger,
rather than the CLR Debugger. In most cases, the information is applicable to both
debuggers. However, you will find sections of the documentation describing some
features that are not implemented in the CLR Debugger (see the next paragraph). You
can simply ignore these features and sections.

Here are some of the main differences between the CLR Debugger and the Visual Studio
Debugger as described in the documentation:
* The CLR Debugger does not support the debugging of Win32 native code applications.
Only applications written and compiled for the common language runtime can be
debugged with the CLR Debugger.

* Remote debugging is not implemented in the CLR Debugger.

* The Registers window is implemented in the CLR Debugger, but no register


information appears in the window. Other operations that involve registers or
pseudoregisters, such as displaying or changing a register value, are not supported. For
more information see, How to: Use the Registers Window.

* The Disassembly window is implemented in the CLR Debugger but shows the
disassembly code that would be generated for the application if it were compiled as
Win32 native code rather than common language runtime code. For more information
see, How to: Use the Disassembly Window.

* The CLR Debugger does not support F1 help.

* The CLR Debugger does not support the Autos window feature.

Click for more details http://msdn.microsoft.com/en-us/library/7zxbks7z(VS.80).aspx

Difference Between String and StringBuilder


String Class
Once the string object is created, its length and content cannot be modified.
Slower
StringBuilder
Even after object is created, it can be able to modify length and content.
Faster

What is Microsoft Intermediate Language (MSIL)?

A .NET programming language (C#, VB.NET, J# etc.) does not compile into executable
code; instead it compiles into an intermediate code called Microsoft Intermediate
Language (MSIL). As a programmer one need not worry about the syntax of MSIL -
since our source code in automatically converted to MSIL. The MSIL code is then send
to the CLR (Common Language Runtime) that converts the code to machine language,
which is, then run on the host machine. MSIL is similar to Java Byte code.
MSIL is the CPU-independent instruction set into which .NET Framework programs are
compiled. It contains instructions for loading, storing, initializing, and calling methods on
objects.
Combined with metadata and the common type system, MSIL allows for true cross-
language integration Prior to execution, MSIL is converted to machine code. It is not
interpreted.
Give Some Examples of Generic Classes?
List<T>,Queue<T>,Stack<T>,LinkedList<T>,HashSet<T>

Can we declare an array variable with var keyword in C# 3.0?


No, var keyword is used to declare implicitly typed local variable. An implicitly typed
local variable is strongly typed just as if you had declared the type yourself, but the
compiler determines the type.

So you can declare a local variable of any type using var keyword but you can't declare
an array of variable using var keyword.

Correct
string[] str = { "ram", "sham" };

foreach (var s in str)

{ Response.Write(s + "<br />"); }

Wrong
var[] str = { "ram", "sham" };

foreach (var s in str)

{Response.Write(s + "<br />"); }


This will throw "CS0246: The type or namespace name 'var' could not be found (are you
missing a using directive or an assembly reference?) " error.
For more info on var keyword see
http://msdn.microsoft.com/en-us/library/bb383973.aspx

Is it possible to notify application when item is removed from cache ?


Yes.
You can use CacheItemRemovedCallback delegate defining signature for event handler
to call when item is removed from cache.
HttpRuntime.Cache.Insert( "CacheItem1", //insert cache item
"",null,Cache.NoAbsoluteExpiration,new TimeSpan(0, 0, 15),
CacheItemPriority.Default,new
CacheItemRemovedCallback(RemovalMethod)); //define method which needs to
be called when item is removed from cache
the method will be like,
private static string RemovedAt = string.Empty;
public static void RemovalMethod(String key, object value, //method is
declared static so that it can be available when cache item is deleted
CacheItemRemovedReason removedReason)
{RemovedAt = "Cache Item Removed at: " + DateTime.Now.ToString();
//Shows the time when cache item was removed
}

How can you cache Multiple Versions of a Page?


Using output cache you can cache multiple versions of the page.

We can either use,… - @ OutputCache directive at design time declaratively for


Declarative Approach
OR
- Response.Cacheclass at runtime for Programmatic Approach.

With @ OutputCache directive four parameters of VaryByParam , VaryByControl,


VaryByHeader, VaryByCustom allows user to cache page depending on query string,
control value, request's HTTP header, request's HTTP header respectively.
For an example:
To turn off caching,
Declarative Approach:
<%@ OutputCache Location="None" VaryByParam="None" %>
Programmatic Approach:
Response.Cache.SetCacheability(HttpCacheability.NoCache);

To cache the output for each HTTP request that arrives with a different ID:
Declarative Approach:
<%@ OutputCache duration="60" varybyparam=" ID" %>

Programmatic Approach:
Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
Response.Cache.SetCacheability(HttpCacheability.Public);
Response.Cache.VaryByParams["ID"] = true;

You have to make user to enter just integer values with TextBox. Can you do this with
CompareValidator?
Yes. With the validator control, you need to set type attribute to the desired datatype
which in this case is “Integer” and Operator to DataTypeCheck.
<asp:CompareValidator ID="CompareValidator1"
ControlToValidate="TextBox1" Type="Integer" Operator="DataTypeCheck"
runat="server" ErrorMessage="CompareValidator"></asp:CompareValidator>

How to Find Number of Days for provided date range?

Code extract :
TimeSpan DayDifference = Convert.ToDateTime("2009-1-
7").Subtract(Convert.ToDateTime("2009-1-1"));
To find the difference of the days, here we have used Subtract method. The Subtract
method does not take start date into consideration. Hence, to get the exact number of days
for the date range we need to add one more day to the result.
Response.Write("Number of Days : " + DayDifference.Days+1);

Can we throw exception from catch block ?


Yes. The exceptions which can’t be handled in the defined catch block are thrown to its
caller.
What first action compiler will take on detection of iterator ?
As soon as compiler will detect iterator, it will automatically generate current, MoveNext
and Dispose methods of the IEnumerator or IEnumerator(T) type.

What is obsolete method?

Obsolete means old or no longer in use. We can define a method as obsolete using
Obsolete keyword/attribute.
[Obsolete]
public int Fun1()
{//Code goes here.}
or
[Obsolete("Any user define message")] public int Fun1()

{//Code goes here..}


One thing to note here is O is always capital in Obsolete.

Can you have different access modifiers on the get/set methods of a property in C#?

No. it's not possible. The access specifier has to be same for get and set.

What is optional and named parameter in C#4.0?

Optional parameter allows omitting arguments to function while named parameters allow
passing arguments by parameter name.
By declaring below variable you are assigning default values to second and third
parameter of 2 and 3 respectively (param2 and param3).
public void optionalParam(int Param1, int param2 = 2, int param3 = 3);

After this you can write,


optionalParam(1); //which will be equivalent to optionalParam(1,2,3);

Sometimes, you may need to not to pass param2. But, optionalParam(1,,3) is not valid
statement with C#. At this point, named parameter comes to the picture.

You can specify arguments like,


optionalParam(1, param3:10); //which will be equivalent to
optionalParam(1,2,10);

What is the difference between a.Equals(b) and a == b?

For value types : “==” and Equals() works same way : Compare two objects by
VALUE
Example:
int i = 5;
int k= 5;
i == k > True
i.Equals(k) > True

For reference types : both works differently :


“==” compares reference – returns true if and only if both references point to the SAME
object while
"Equals" method compares object by VALUE and it will return true if the references
refers object which are equivalent
Example:
StringBuilder sb1 = new StringBuilder(“Mahesh”);
StringBuilder sb2 = new StringBuilder(“Mahesh”);
sb1 == sb2 > False
sb1.Equals(sb2) > True

But now look at following issue:


String s1 = “Mahesh”;
String s2 = “Mahesh”;
In above case the results will be,
s1 == s2 > True
s1.Equals(s2) > True
String is actually reference type : its a sequence of “Char” and its also immutable but as
you saw above, it will behave like Value Types in this case.
Exceptions are always there ;)

Now another interesting case:


int i = 0;
byte b = 0;
i == b > True
i.Equals(b) > False
So, it means Equals method compare not only value but it compares TYPE also in Value
Types.

Recommendation :
For value types: use “==”
For reference types: use Equals method.

What is the difference between Parse and TryParse method?

Parse method is used to parse any value to specified data type.


string test = "42";
int32 Result;
Result = Int32.Parse(test);

This will work fine bt what if when you are aware about the value of string variable test.

if test="abc"....

In that case if u try to use above method, .NET will throw an exception as you are trying
to convert string data to integer.

TryParse is a good method if the string you are converting to an interger is not always
numeric.
if(!Int32.TryParse(test,out iResult))
{ //do something }
The TryParse method returns a boolean to denote whether the conversion has been
successfull or not, and returns the converted value through an out parameter.

**declare variable iResult of Int32.

Can we define generics for any class?

No, generics is not supported for the classes which does not inherits collect class.

C# delegate keyword is derived from which namespace?

C# delegate keyword is derived form System.MulticastDelegate.

What will be the length of string type variable which is just declared but not assigned any
value?
As variable is not initialized and it is of reference type. So it's length will be null and it
will throw a run time exception of "System.NullReferenceException" type, if used.

How do we retrieve day, month and year from the datetime value in C#?

Using the methods Day,Month and Year as follows


int day = dobDate.Day;
int month = dobDate.Month;i
int year = dobDate.Year;

I need to restrict a class by creating only one object throughout the application.
How can I achieve this?

We can declare the constructor of the class as either protected or as private


How can you make your machine shutdown from your program?
Process.Start("shutdown", "-s -f -t 0");

What is the use of unsafe keyword in C#?

In C# the value can be directly referenced to a variable, so there is no need of pointer.


Use of pointer sometime crashes the application. But C# supports pointer, that means we
can use pointer in C#.

The use of pointer in C# is defined as a unsafe code. So if we want to use pointer in C#


the pointer must be present in the body of unsafe declaration. But pointer does not come
under garbage collection.

Example:-

unsafe
{
int a, *b;
a = 25;
b = &a;
Console.WriteLine("b= {0}",b);//returns b= 25
}

What is difference between var and Dynamic ?


Var word was introduced with C#3.5(specifically for LINQ) while dynamic is introduced
in C#4.0. variables declared with var keyword will get compiled and you can have all its
related methods by intellisense while variables declared with dynamic keyword will
never get compiled. All the exceptions related to dynamic type variables can only be
caught at runtime.

What is dynamic keyword ?

Its newly introduced keyword of C#4.0. To indicate that all operations will be performed
runtime.

What will happen if you declare a variable named "checked" with any data type?

Compiler will throw an error as checked is a keyword in C# So It cannot be used as


variable name. Checked keyword is used to check the overflow arithmetic checking.

What are anonymous methods?


Anonymous methods are another way to declare delegates with inline code except named
methods.

Restrictions of yield in try-catch.

While using yield keyword, mainly two restrictions are observed.


First is , we can’t use yield in finally.
Second is , we can’t place yield keyword in the catch block if try contains more than one
catch blocks.

What is the use of param keyword in C#?

In C# param parameter allows us to create a method that may be sent to a set of


identically typed arguments as a single logical parameter.

Which class defines different events for controls in C#?


The "Control" class defines a number of events that are common to many controls.

What do you mean by properties in C#?

Property acts as a cross link between the field and the method . Actually it behaves as
a field. We can retrieve and store data from the field using property.
The compiler automatically translates the field like property into a call like special
method called as 'accessor" . In property there are two accessor and that are used to save
value and retrieve value from the field. The two properties are 'get' and 'set'.
The get property is used to retrieve a value from the field and the set property is used to
assign a value to a field .
Depending on there use properties are categorised into three types,
ReadWrite Property :- When both get and set properties are present it is called as
ReadWrite Property.
ReadOnly Property :- When there is only get accessor it is called as ReadOnly Property.

WriteOnly Property :- When there is only set accessor, it is called as WriteOnly


Property.

What are the different method parameter modifiers in C#?

out
ref
params
What are the different Iteration Constructs in C#?

for loop
foreach/in loop
while loop
do/while loop

What is the use of ?? operator in C#?


This operator allows you to assign a value to a nullable type if the retrieved value is in
fact null.

What is the CIL representation of implicit and explicit keywords in C#?


The CIL representation is op_Implicit and op_Explicit respectively.

Which operators in C# provides automatic detection of arithmetic overflow and


underflow conditions?
'checked' and 'unchecked' keywords provide automatic detection of arithmetic overflow
and underflow conditions.

What is the use of stackalloc keyword in C#?


In an unsafe context it is used to allocate C# array directly on the stack.

Which keyword in C# is used to temporarily fix a variable so that its address may be
found?
fixed keyword

What are the different C# preprocessor directives?

#region , #endregion :- Used to mark sections of code that can be collapsed.

#define , #undef :-Used to define and undefine conditional compilation symbols.

#if , #elif , #else , #endif :- These are used to conditionally skip sections of source code.

What is the use of GetInvocationList() in C# delegates?

GetInvocationList() returns an array of System.Delegate types, each representing a


particular method that may be invoked.

Which methods are used to execute javascript code from code behind file?
RegisterStartupScript and RegisterClientScriptBlock

If i will write a piece of code in finaly block, will it execute if there is an exception in try
block.
Yes, the code in finally block will execute.

Why 'static' keyword is used before Main()?


Program execution starts from Main(). So it should be called before the creation of any
object. By using static the Main() can now be called directly through the class name and
there is no need to create the object to call it. So Main() is declared as static.

What is CharEnumerator in C#?

CharEnumerator is an object in C# that can be used to enumerate through all the


characters of a string. Below is the sample to do that
string str = "my name";
CharEnumerator chs = str.GetEnumerator();
while(chs.MoveNext())
{
Response.Write(chs.Current);
}
Moderator: please do not move this to Code section, this is a typical interview question
that was asked :)

I would like to find all the directories of a folder How should I achieve this?
By Directory.GetDirectories method

Tell me one reason for dotnet doesn't have multiple inheritance

To avoid ambiguity and deadlocks

How can you check a nullable variable is assigned?

using hasvalue method

what is the syntax of a nullable variable?


Nullable myval=null;

I would like to check a variable as assigned or not. How can we do that?

Declare the variable as Nullable

What are the different compiler generated methods when a .NET delegate is
compiled?
Compilation of a .NET delegate results in a sealed class with three compiler generated
methods whose parameters and return values are dependent on the delegate declaration.
The methods are, Invoke() BeginInvoke() and EndInvoke().
When TimerCallback delegate is used?
Many application have the need to call a specific method during regular intervals. For
such situations we can use the System.Threading.Timer type in conjunction with a related
delegate named TimerCallback.

Which enumeration defines different PenCap in C#?


LineCap enumeration which defines different pen cap styles as follows,
public enum LineCap
{
Flat, Square, Round, Triangle, NoAncher, SquareAnchor,
RoundAnchor, DiamondAnchor, ArrowAnchor, AnchorMask, Custom
}

Some facts about Virtual methods.

Virtual keyword is used to declare a method inside the base class that can be overridden.
Following conditions are applied to a virtual method
1. Virtual method can not be declared as Private
2. Virtual method can not be declared as Static
3. Virtual method may or may not be overridden.
4. In order to override the virtual method of the base class, Override keyword is used
provided the method signature of the derived class is same as base class, even the access
modifier should be same.
5. A Virtual method must contain the method body otherwise compiler shall throw error.
6. Virtual keyword is only used in base and derived class scenario where you want your
method over-ridable in the derived class.

What is the difference between IQueryable<T> and IEnumerable<T> interface?

IEnumerable<T>
IEnumerable<T> is best suitable for working with in-memory collection.
IEnumerable<T> doesn't move between items, it is forward only collection.

IQueryable<T>
IQueryable<T> best suits for remote data source, like a database or web service.
IQueryable<T> is a very powerful feature that enables a variety of interesting deferred
execution scenarios (like paging and composition based queries).

So when you have to simply iterate through the in-memory collection, use
IEnumerable<T>, if you need to do any manipulation with the collection like Dataset and
other data sources, use IQueryable<T>.
Can we declare a class as Protected?
No, a class can not be declared as Protected.

A class can be declared with only following access modifiers.

Abstract
Internal
Public
Sealed
Static
Extern (The extern modifier is used to declare a method that is implemented externally. -
http://msdn.microsoft.com/en-us/library/e59b22c5(VS.80).aspx)

Can we inherit a private class into the public class?

No, In C#, a derived class can’t be more accessible than it’s base class. It means that you
can't inherit a private class into a public class. So always the base class should be more or
equal accessible than a derived class.
// Following will throw compilation error
private class BaseClass
{}
public class DerivedClass : BaseClass
{}

// Following will compile without an error


public class BaseClass
{}
public class DerivedClass : BaseClass
{}

what is the class used for dealing with graphics objects

System.Drawing.Graphics is the class used for dealing with graphics objects

Name any two "Permission Classes" generally used while working with CAS ?
1) FileIOPermission
2) UIPermission
3) SecurityPermission

Write a way to read an image from a path to a bitmap object

We can directly read an image file and load it into a Bitmap object as below.
Bitmap myBmpObj = Bitmap.FromFile(strPath);
We can also set Image path during the Initilization of Bitmap Object. Code as given
below.
Bitmap loBMP = new Bitmap(strPath);

How we can gt the values of control on the previous page in case of server.transfer
method?

Using Page.PreviousPage.FindControl() method.

Can we use Page.PreviousPage to get the value of controls of the previous page in case of
response.Redirect ?
No, we can't use PreviousPage to find the control on previous page with
response.redirect.

What is the page size in SQL Server?


8 KB -- > 8192
you can check this with the query :
SELECT low FROM master..spt_values WHERE number = 1 AND type = 'E'

What is the main difference between RegisterStartUpScript and


RegisterClientScriptBlock?

RegisterStartUpScript Add the javascript code at the end of the page before the closing of
form tag. while RegisterClientScriptBlock place the code at the top of the page.

Serialization/Deserialization in .NET
Welcome to the next installment of the .NET Nuts & Bolts. In this column, we'll explore
serialization and deserialization with the Microsoft .NET Framework. We'll look at the
reasons for using serialization and techniques for utilizing it within your applications. It
will involve using classes located in the System.Runtime.Serialization namespace.

Definition of Serialization

Serialization is the process of taking an object and converting it to a format in which it


can be transported across a network or persisted to a storage location. The storage
location could be as simple as using a file or a database. The serialized format contains
the object's state information. Deserialization is the process of using the serialized state
information to reconstruct the object from the serialized state to its original state. In
essence, the process of serialization allows an object to be serialized, shipped across the
network for remoting or persisted in a storage location such as the ASP.NET cache, and
then be reconstructed for use at a later point in time.
Serialization Formats

There are three formats provided by the Microsoft .NET framework to which objects can
be serialized. The formats are binary, SOAP, and XML. The format is controlled based
upon what object is used to perform the serialization. The XML format is produced by
using the System.Xml.Serialization.XmlSerializer class. The SOAP and binary formats
are produced by using classes under the System.Runtime.Serialization.Formatters
namespace.

There are subtle differences among the serialized formats. The binary-based format is the
most compact and light of the three formats. The XML formatter only serializes public
fields and properties, while binary and SOAP do not adhere to that limitation.

Controlling XML Serialization with Attributes


o Attributes can be used to control the serialization of an object performed
by the XmlSerializer. Some of the attributes available are as follows:
 XmlAttributeAttribute—The member will be serialized as an XML attribute
 XmlElementAttribute—The field or property will be serialized as an XML
element
 XmlIgnoreAttribute—The field or property will be ignored when serializing
 XmlRootAttribute—Represents the XML document's root element name, only
applies to a class

XML Serialization Sample Code

The following code defines a class that demonstrates the use of some of the XML
serialization controlling attributes.

using System;
using System.Xml.Serialization;

namespace CodeGuru.Serialization
{
[XmlRoot("TestDataXml")]
public class TestData
{
private int _Identity = 0;

private string _Name = "";


[XmlElement("DataName")]
public string Name
{
get { return this._Name; }
set { this._Name = value; }
}

private string _IgnoreMe = "";


[XmlIgnore]
public string IgnoreMe
{
get { return this._IgnoreMe; }
set { this._IgnoreMe = value; }
}

public TestData()
{
}
}
}

Test XML Serialization Code

The following code will serialize the sample class defined above and store the
information in a file on the local drive.

TestData obj = new TestData();


obj.Name = "testing";
obj.IgnoreMe = "ignore";
XmlSerializer serializer = new XmlSerializer(obj.GetType());
Stream stream = new FileStream("c:\\MyFile.xml", FileMode.Create,
FileAccess.Write, FileShare.None);
serializer.Serialize(stream, obj);
stream.Close();

Resulting XML

Notice how the private fields and properties are not included in the XML. The
XmlSerializer behaves this way by design.

<?xml version="1.0"?>
<TestDataXml xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<DataName>testing</DataName>
</TestDataXml>
Delay signing allows to place a shared assembly in the GAC
by signing the assembly with just the public key. This
allows the assembly to be signed with the private key at a
later stage, when the development process is complete and
the component or assembly is ready to be deployed.

This process enables developers to work with shared


assemblies as if they were strongly named, and it secures
the private key of the signature from being accessed at
different stages of development.

Step 1. Create a public Key File for Delay Signing

To create a public key file for delay signing

1. Create a key pair for your organization.sn.exe -k keypair.snk


2. Extract the public key from the key pair file. sn -p keypair.snk publickey.snk
3. Protect Keypair.snk, which contains both the private and public keys. For
example, put it on a compact disc or other hardware device, such as a smart card,
and physically secure it.
4. Make Publickey.snk available to all developers. For example, put it on a network
share.

Step 2. Delay Sign Your Assembly


1. In Visual Studio .NET 2005, display the project properties.
2. Click the Signing tab, and select the Sign the assembly and Delay sign only
check boxes.
3. In the Choose a strong name key file: drop-down box, select <Browse…>.
4. In the file selection dialog box, browse to the public key (.snk) and click OK.
5. Build your assembly. The complier will build a strong named assembly signed
using the public key from the selected key pair (.snk) file. Note A delay signed
project will not run and cannot be debugged. You can, however, use the Strong
Name tool (Sn.exe) with the -Vr option to skip verification during development.
6. The delay signing process and the absence of an assembly signature means that
the assembly will fail verification at load time. To work around this, use the
following commands on development and test computers.
o To disable verification for a specific assembly, use the following
command.

sn -Vr assembly.dll

o To disable verification for all assemblies with a particular public key, use
the following command.

sn -Vr *,publickeytoken

o To extract the public key and key token (a truncated hash of the public
key), use the following command.

sn -Tp assembly.dll Note Use an uppercase -T switch.

7. To fully complete the signing process and create a digital signature to make the
assembly tamper proof, execute the following command. This requires the private
key, and as a result the operation is normally performed as part of the formal
build/release process. The following command uses key pair contained in the
Keypair.snk file to re-sign an assembly called Assembly.dll with a strong name.
sn -R assembly.dll keypair.snk Done

Attributes

Attributes provide a powerful method of associating declarative information with C#


code (types, methods, properties, and so forth). Once associated with a program entity,
the attribute can be queried at run time and used in any number of ways.
 Declaring an Attribute Class The first thing you need to be able to do is declare an
attribute.
 Using an Attribute Class Once the attribute has been created, you then associate
the attribute with a particular program element.
 Accessing Attributes Through Reflection Once the attribute has been associated
with a program element, you use reflection to query its existence and its value.
http://www.codeproject.com/KB/dotnet/Custom_Attributes.aspx

C# Interview Questions (Mercer Company Gurgaon)

1. What is OOPs?

2. What is Object?

3. What is Abstract Class?

4. What is abstract function?

5. What is Arraylist, what type of data it store?

6. Boxing and Unboxing?

7. Override and New keywords?

8. Sealed Class?

9. How can you stop a class being inherited?

10. How can you stop class being instantiated?

11. What is interface?

12. Multilevel and Multiple inheritance?

13. How can you handle abstract function without implementing it in derive class?

14. List the datagrid events?

15. How many number of times item data bound event will be called for 10 rows in grid?
What property will you use to check header in datagrid?

16. What is HTTP handler? How will you implement?


17. Write a code to add a user control to a page?

18. Difference between user control and custom user control?

19. How many master page a project can have?

20. Write a code to add msterpage in a page?

21. Difference between string and string builder?

22. types of Design patterns? Implement one of them?

23. What is UML ? Design a UML diagram?

24. What is MVC?

25. Can we have multiple update panel in AJAX, Write a code to call another update
panel on click on another?

26. what are collections?

27. delegate and events?

You might also like