Thursday, November 17, 2005

C Sharp Interview Questions

1. The C# keyword ‘int’ maps to which .NET type?
Ans. System.Int32

2. What string definition prevents escaping on backslashes in C#?
Ans. string s = @"n Test string";

3. What statement correctly declares a two-dimensional array in C#?
Ans. int[,] myArray;

4. If a method is marked as protected internal who can access it?
Ans. Classes within the same assembly, and classes derived from the declaring class.

5. What is boxing?
Ans. Encapsulating a copy of a value type in an object.

6. What compiler switch creates an xml file from the xml comments in the files in an assembly?
Ans. /doc Switch creates an XML file from XML Comments.

7. What is a satellite Assembly?
Ans . An assembly containing localized resources for another assembly.

8. What is a delegate?
Ans. A strongly typed function pointer.

9. How does assembly versioning in .NET prevent DLL Hell?
Ans. .NET allows assemblies to specify the name AND the version of any assemblies they need to run.

10. In the NUnit test framework, which attribute must adorn a test class in order for it to be picked up by the NUnit GUI?
Ans. TestFixtureAttribute

11. Which of the following operations can you NOT perform on an ADO.NET DataSet?
Ans. A DataSet can be synchronised with a RecordSet.

12. In Object Oriented Programming, how would you describe encapsulation?
Ans. The separation of interface and implementation.

Q1. Basic Inheritance:

What results would you expect from running the code below?

using System;
class A
public void F() { Console.WriteLine("A.F"); }
public virtual void G() { Console.WriteLine("A.G"); }
class B: A
new public void F() { Console.WriteLine("B.F"); }
public override void G() { Console.WriteLine("B.G"); }
class Test
static void Main() {
B b = new B();
A a = b;

Q2. More Inheritance:

What results would you expect from running the code below?

using System;

class A
public virtual void F() { Console.WriteLine("A.F"); }
public void G() { Console.WriteLine("A.G"); }
class B: A
public override void F() { Console.WriteLine("B.F"); }
new public virtual void G() { Console.WriteLine("B.G"); base.G(); }
class C: B
new public virtual void F() { Console.WriteLine("C.F"); }
new public virtual void G() { Console.WriteLine("C.G"); base.G(); }
class D: C
public override void F() { Console.WriteLine("D.F"); }
public override void G() { Console.WriteLine("D.G"); base.G(); }
class Test
static void Main()
D d = new D();
A a = d;
B b = d;
C c = d;

Console.WriteLine("---END A---");

Console.WriteLine("---END B---");

Console.WriteLine("---END C---");

Console.WriteLine("---END D---");

D e = new D();
B f = e;
Console.WriteLine("---END E---");


Q3. What does the ThreadStatic attribute do?

Q4. What does the "Volatile" modifier do?
The volatile keyword indicates that a field can be modified in the program by something such as the operating system, the hardware, or a concurrently executing thread.
volatile declaration
The declaration of a field.
The system always reads the current value of a volatile object at the point it is requested, even if the previous instruction asked for a value from the same object. Also, the value of the object is written immediately on assignment.
The volatile modifier is usually used for a field that is accessed by multiple threads without using the lock statement to serialize access. Using the volatile modifier ensures that one thread retrieves the most up-to-date value written by another thread.
The type of a field marked as volatile is restricted to the following types:
· Any reference type.
· Any pointer type (in an unsafe context).
· The types sbyte, byte, short, ushort, int, uint, char, float, bool.
· An enum type with an enum base type of byte, sbyte, short, ushort, int, or uint.
For more information on volatile, see 10.4.3 Volatile fields.
The following sample shows how to declare a public field variable as volatile.
// csharp_volatile.cs
class Test
public volatile int i;

Test(int _i)
i = _i;
public static void Main()


Q5. Does C# support multiple inheritance?
No, Just by Using Interfaces.

Q6. When you inherit a protected class-level variable, who is it available to?

Q7. Describe the accessibility modifier "protected internal".

Q8. C# provides, by default a parameterless constructor. If I write a constructor that takes a string as a parameter, but want to keep the parameterless constructor. How many constructors should I write?

Q9. Can you allow a class to be inherited, but prevent a method from being overridden?

Q10. What's the difference between an interface and abstract class?

Q11. If a base class has overloaded constructors, and an inherited class also has overloaded constructors, can you enforce a call from an inherited constructor to an arbitrary base constructor?

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

Q13. What is the difference between the [EditorBrowsable] and [Browsable] attributes?

Q14. Can multiple catch blocks be executed?
Yes, with different exception.

Q15. If an exception is thrown inside a catch block, will the finally block be still be called?

Q16. If none of the catch blocks contain a matching exception type, what will happen?

Q17. Explain ACID rule of thumb for transactions.

Q18. Write code to resize a System.Drawing.Rectangle, decreasing it's width and height by one unit.

Q19. Virtual/Static Methods:
a) Can you declare an overriden method as static?
b) Can a static method be declared as virtual?
c) Can you override a private virtual method?
d) Can an interface method be declared as virtual?

Q20. Describe the different database locking mechanisms you have used and discuss their merits.

Q21. How would you go about making an object cloneable (inc. interface/s and namespaces)?

Q22. What's the difference between and background and foreground thread?

Q23. Structs v Classes.
What results would you expect from the following and why?

using System;

class HumanClass
public string Name;

struct HumanStruct
public string Name;

class RunTest
public static void ChangeName(HumanStruct human)
human.Name = "James";

public static void ChangeName(HumanClass human)
human.Name = "James";

public static void ChangeName(ref HumanStruct human)
human.Name = "James";

public static void ChangeName(ref HumanClass human)
human.Name = "James";

public static void Main()
HumanStruct a = new HumanStruct();
HumanClass b = new HumanClass();
a.Name = "Andrew";
b.Name = "Andrew";

Console.WriteLine("Val Calls");
Console.WriteLine("a.Name = {0}", a.Name);
Console.WriteLine("b.Name = {0}", b.Name);

Console.WriteLine("Ref Calls");
a.Name = "Andrew";
b.Name = "Andrew";

ChangeName(ref a);
ChangeName(ref b);
Console.WriteLine("a.Name = {0}", a.Name);
Console.WriteLine("b.Name = {0}", b.Name);



a) Can a struct inherit from another struct?
b) Can a struct inherit from another class?
c) Can a struct be the base of another class?
d) Can a struct implement an interface?

Q25. Finalizers

a) Describe the basic process of finalization.
b) When should you use a finalizer?
c) What access protection should you give your finalizer?
d) Write a stub class which impliments both a finaliser and the IDisposable interface. Demonstrate how to prevent a disposed objects from being finalized.
e) How and when would you go about preventing the finalizer being called for a specific object?

Q 26. Arrays

a) What is the difference between a rectangular and jagged array?
b) Write the declaration for a 3d rectangular and 3d jagged array.
c) Does the Clone method of an array perform a deep or shallow copy (explain the difference between the two)?

Q 27. Value Types

Write the code to define a new value type called "Andrew" which overloads the inequality and equality operators, and overrides the equality operator. The value type must have a single integer property called "Age" which should be used in the compairsons. The code below demonstrates a simple test for the new value type:

Andrew a = new Andrew(), b = new Andrew();
a.Age = 10;
b.Age = 10;

// This should return true
Console.WriteLine(b == a);

a.Age = 11;
// This should return false
Console.WriteLine(b == a);

Q 28. Explicit Interfaces

a) Will the following class compile?
b) Discuss the way the interface has been implimented and when would you use this?

interface ISomeInterface
string Key{ get; }

public class myClass : ISomeInterface
/// Gets the object key.

public string Key
get{ return "Andrew"; }

/// Gets the object key.

public string ISomeInterface.Key
/// Delegate the inteface call to the Key property.
get{ return this.Key; }

Q 29. Dates

Write a simple function that takes a date and return which quarter that date is in (ie dates from January through to March will return 1, dates from April through to June will return 2 etc).

Q 30. Iterators

Write some example source code iterating through a collection using GetEnumerator(). What
is the difference between using GetEnumerator() and writing a foreach loop?

Q 31. IDisposable

Write the results you would expect to see from running the following code:

class EntryPoint
static void Main(string[] args)
TestResource test = new TestResource("TEST 1");
throw new Exception("TEST MESSAGE");

TestResource test = new TestResource("TEST 2");
test = null;

using( TestResource test = new TestResource("TEST 3") )
throw new Exception("TEST MESSAGE");


class TestResource: IDisposable
private string _disposeMessage = string.Empty;

/// Default constructor.

/// Dispose message
public TestResource(string disposeMessage)
_disposeMessage = disposeMessage;

/// Disposes of resources.

public void Dispose()
Console.WriteLine( "{0}. Message {1}. Dispose Called", DateTime.Now, _disposeMessage );

Q 32. Value and Reference Type Conversions

a) What output would you expect the following code to return and explain what's happening?

struct Point
public int x, y;
public Point(int x, int y)
this.x = x;
this.y = y;

Point p = new Point(10, 10);
object refPoint = p;
p.x = 20;

b) What would you expect the following code to return and comment on the difference between the comparisons:

string a = "hello";
string b = "h";
string c = "hello";
b += "ello"; // append to b
string d = String.IsInterned(b);
Console.WriteLine( "Test 1: " + (a == b) );
Console.WriteLine( "Test 2: " + Object.Equals( a, b) );
Console.WriteLine( "Test 3: " + ((object)a == (object)b) );
Console.WriteLine( "Test 4: " + Object.ReferenceEquals(a, c) );
Console.WriteLine( "Test 5: " + (c == a) );
Console.WriteLine( "Test 6: " + Object.ReferenceEquals(a, d) );

Q 33. Reference to a Value type

Write example code that obtains a reference to a value type (eg a struct) and prove that the reference points to this value type.

Q 34. Basic Maths

a) Carefully add the following numbers in your head.

Take 1000 and add 40 to it. Now add another 1000. Now add 30. Add
another 1000. Now add 20. Now add another 1000
Now add 10. What is the total?

b) Calculate 19 * 17 in your head?

Q 35. Logic

Think carefully before giving your answer.

a) You are participating in a race. You overtake the second person.
What position are you in?

b) If you overtake the last person, then what position are you in?

Q 36. Case Statements

What will happen in each of the following case statement blocks?


int x = 1;
case 0:
case 1:
Console.WriteLine("X = " + x.ToString() );


int x = 1;
case 0:
Console.WriteLine("X = " + x.ToString() );
case 1:
Console.WriteLine("X = " + x.ToString() );
Console.WriteLine("X = " + x.ToString() );


int x = 1;
case 0:
goto case default;
case 1:
goto case default;
Console.WriteLine("X = " + x.ToString() );

Q 37. Basic Delegates

Definate a delegate to call the "MyFunction" method of the "CallOnMe" class. Your
code should also include an example of how to invoke and return the results from this
delegate. The class is defined below:

public class CallOnMe
public string MyFunction(string myValue)
return "Answer: " + myValue ;

Q 38. Basic Database and ADO Questions

a) What is the role of the DataReader class in ADO.NET connections?
b) What is a pre-requisite for connection pooling?

Q 39. ASP.NET Basics

a) Explain the differences between Server-side and Client-side code?
b) What are some ways to manage state in an ASP.Net application?
c) What does the "EnableViewState" property do? Why would I want it on or off?
d) What is the difference between Server.Transfer and Response.Redirect? Why would I choose one over the other?
e) How can I maintain Session state in a Web Farm or Web Garden?
f) What base class do all Web Forms inherit from?
g) What does WSDL stand for? What does it do?
h) Which WebForm Validator control would you use if you needed to make sure the values in two different WebForm controls matched?
i) What property must you set, and what method must you call in your code, in order to bind the data from some data source to the Repeater control?

Q 40. Architecture

a) Describe the three tier or n-Tier model.
b) Name some of the Microsoft Application Blocks. Have you used any? Which ones?

Q 41. Basic Locking

a) Describe the two different locking strategies employed in the code below.
b) Which (if any) of these strategies guarantee method level synchronisation to a collection?
c) How do you create a synchronised hashtable? What considerations need to be made when using enumerators on synchronised collections?
d) What is the point of the SyncRoot object?

// Define two hashtables
private static Hashtable _ht1;
private static Hashtable _ht2;

static void Main(string[] args)
// Create collection
_ht1 = new Hashtable();
_ht2 = new Hashtable();

// Create threads
Thread th1 = new Thread( new ThreadStart( _TestLock1 ) );
Thread th2 = new Thread( new ThreadStart( _TestLock2) );
// Start threads

// Wait for threads to startup

// Add to hash tables
_ht1.Add( "-1",-1);
_ht2.Add( "-1",-1);

/// Adds to Hashtable 2

private static void _TestLock1()
// Lock the SyncRoot object
lock( _ht1.SyncRoot )
// Add to has table
for ( int i = 0 ; i < 200; i++ )
_ht1.Add ( i.ToString(), i );
Thread.Sleep( 1000 );

/// Adds to Hashtable 2

private static void _TestLock2()
// Lock the hashtable object
lock( _ht2 )
// Add to has table
for ( int i = 0 ; i < 200; i++ )
_ht2.Add ( i.ToString(), i );
Thread.Sleep( 1000 );

Q 42. Interfaces

Will the code below compile? If so, write code to return the string "Driving my car home".

public abstract class Car
public virtual void Start() {}
public virtual void Park() {}

public interface ICompanyCar
string Drive();

public interface IPersonalCar
string Drive();

public class MyCar : Car, ICompanyCar, IPersonalCar
string ICompanyCar.Drive()
return "Driving my car to work";
string IPersonalCar.Drive()
return "Driving my car home";

Q 43. Interface Members

Which of the following can be an interface member?

a. Constructors or destructors
b. Static members
c. Constants
d. DataFields
e. Events
f. Finalizers

Q 44. Static Constructors

When is a static constructor called?

a. When the application is first loaded into memory.
b. After the first instance of the class is created.
c. Before the first instance of the class is created, or before the first static method is called.
d. Static constructors are indeterminate, ie. they are called at unpredictable times.

Q 45. Operators

Describe what results you would expect to see returned from the following and explain why:

public enum myEnum

class TestClass
static void Main(string[] args)
Console.WriteLine( "1 " + Equals1( myEnum.x, myEnum.x ) );
Console.WriteLine( "2 " + Equals2( myEnum.x, myEnum.x ) ) ;
Console.WriteLine( "3 " + Equals3( myEnum.x, myEnum.x ) );
Console.WriteLine( "4 " + Equals4( myEnum.x, myEnum.x ) );
Console.WriteLine( "5 " + Equals5( myEnum.x, myEnum.x ) );

public static bool Equals1(object x, object y)
return x == y;

public static bool Equals2(myEnum x, myEnum y)
return x == y ;

public static bool Equals3(object x, object y)
return Object.Equals( x , y );

public static bool Equals4(object x, object y)
return x.Equals( y ) ;

public static bool Equals5(object x, object y)
return ((myEnum)x).Equals( y ) ;


Q 46. Operators

Write a small code snippet that demonstrates how you would go about overloading the && and || operators.

Q 47. Remoting

a) What are the consideration in deciding to use .NET Remoting or ASP.NET Web Services?

b) What are remotable objects in .NET Remoting?

c) What’s SingleCall activation mode used for?

d) What’s Singleton activation mode?

e) How do you define the lease of the object?

f) What are channels in .NET Remoting

Q 48. Architecture

What is Cyclomatic complexity?

Q 49. Security Attributes

What benefit does your code receive if you decorate it with attributes demanding specific Security permissions?

Q 50. Native Image Cache

What is native image cache and where is it stored?

Q 51. Shallow Copy, Deep Copy and MemberWiseClone

What is the difference between shallow and deep copying? How does MemberWiseClone method work?

Q 52. General

What does the following code snippet return?

double expectedValue = 1/2;
if ( expectedValue > 0 )
expectedValue = expectedValue + 0.5;


A.F // Not B.F, since since class b uses the "new" keyword which breaks the inheritance tree.


---END A---
---END B---
---END C---
---END D---
---END E---

A static variable marked with ThreadStaticAttribute is not shared between threads. Each executing thread has a separate instance of the field, and independently sets and gets values for that variable. If the variable is accessed on a different thread, it will contain a different value.

Note, do not specify initial values for variables marked with ThreadStaticAttribute, because such initialization occurs only once when the class constructor executes (and therefore only applys to the thread that created the class). Your code should expect the field to be initialized to it's default value for value types, or to a null reference if it is a reference type. Variables marked with the ThreadStaticAttribute are by definition thread safe.

The system always reads the current value of a volatile object at the point it is requested, even if the previous instruction asked for a value from the same object. Also, the value of the object is written immediately on assignment (the ordering of writes and reads is always preserved).

The volatile modifier is usually used for a field that is accessed by multiple threads without using the lock statement to serialize access. Using the volatile modifier ensures that one thread retrieves the most up-to-date value written by another thread.

No, you can only inherit from a single object. But you can expose multiple interfaces.

A derived protected variable is only accessible in the derived class.

The variable or field will be available to derived classes and classes within the same Assembly (+ the base class it?s declared in).

Two. Once you write another constructor, C# will remove the implicit parameterless constructor (unless you are writting a struct which always contain a parameterless constructor).

Yes, just leave the class public and make the method sealed.

In the interface all methods must be abstract, in the abstract class some methods can be concrete. In the interface no accessibility modifiers are allowed, which is ok in abstract classes.

Yes, just place a colon and the keyword "base" followed by the parameter list to invoke the appropriate constructor. You can use the same symantics to invoke other constructors in the current class, using the "this" keyword in place of "base". See below for an example:


// Base class
Public class Person
public Person(string name)
Debug.WriteLine("(Base Class) Person: " + name);

// User class. Derives from person
public class User: Person
public User(string name, int age)
:base(name) // Call the name constructor of the base class
Debug.WriteLine("Person: " + name + " age = " + age.ToString());

public User(string name, int age, string loginName)
:this(name, age) // Call the name, age constructor of this class
Debug.WriteLine("Person: " + name + " age = " + age.ToString() + ", login = " + loginName);


StringBuilder is more efficient in cases where there is a large amount of string manipulation. Strings are immutable, so each time a string variable is altered a new instance will be created.

The intellisense engine uses EditorBrowsableAttribute whereas the property grid control uses the BrowsableAttribute.


You can use this class in a visual designer or text editor to determine what is visible to the user. For example, the IntelliSense engine in Visual Studio .NET uses this attribute to determine whether to show a method or property. The values for this attribute are:

The property or method is a feature that only advanced users should see. An editor can either show or hide such properties.

The property or method is always browsable from within an editor.

The property or method is never browsable from within an editor.


Members marked with the BrowsableAttribute constructor of the value false are not appropriate for design-time editing and therefore are not displayed in a visual designer (property grid). The default is true.

No, once a matching catch exception signature is found the control will be transferred to the finally block (if there are any).

If the catch clauses throws an exception the finally clause WILL be called before the exception is propagated up the call stack.

None of the other catch blocks will be called and the exception will be treated as a unhandled exception (i.e. the exception will be propagated up the call stack). If there is a finally block this will get called before propogating this unhandled exception. Note, a generic exception handler takes the form:

catch(Exception ex)

ACID transactions:

Transaction must be Atomic (it is one unit of work and does not dependent on previous and following transactions).

Data is either committed or rolled back. It cannot be in an "in-between" state, where something has been updated and something has not.

No transaction should see the intermediate results of the current transaction.

The values persist if the data had been committed even if the system crashes right after.

Resize Rectangle:
// Create a rectangle
Rectangle rect = new Rectangle(0, 0, 10, 10);
// Reduce it's width and height by one.
rect.Inflate(-1, -1);

A19. Virtual/Static Methods:
a) No. The signature of an overriden method must remain the same.
b) No. Static methods cannot be virtual.
c) No. Private methods are inaccessible in derived classes. Note, the compiler won't actually allow you to declare a private method as virtual.
d) Yes. Interface methods can be declared as virtual.

Candidate should explode into a lengthy rant and cover the following topics:

a) Optimistic locking - assumes that collisions are unlikely and therefore only gets a lock just before you try to commit your changes.
b) Pessimitic locking - assumes that your changes will collide with another user's and hence locks all the rows you are updating as you read them.
c) Versioning - uses a version number column on each table to detect if any changes have been made. Often useful to have a "last updated" and "last updated by" column as well.
d) Timestamps - same as above but using the timestamp data type gives you an automatically updating column.

Implement "ICloneable" eg:

using System.Runtime.Serialization.Formatters.Binary;

/// Clones this object using a binary formatter (virtual method).

/// Clone of object.
public virtual object Clone()
// Create a new memory stream
using (Stream stream = new MemoryStream())
// Use binary formatter to serialize this object
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(stream, this);
// Reset the position back to the start of the stream
stream.Position = 0;

Below is a list of 49 ASP.NET interview questions

1. Explain the differences between Server-side and Client-side code?
2. What type of code (server or client) is found in a Code-Behind
3. Should validation (did the user enter a real date) occur
server-side or client-side? Why?
4. What does the "EnableViewState" property do? Why would I want it on or off?
5. What is the difference between Server.Transfer and
Response.Redirect? Why
would I choose one over the other?
6. Can you give an example of when it would be appropriate to use a
web service as opposed to a non-serviced .NET component
7. Let's say I have an existing application written using Visual
Studio 6 (VB 6, InterDev 6) and this application utilizes Windows 2000
COM+ transaction services. How would you approach migrating this
application to .NET
8. Can you explain the difference between an ADO.NET Dataset and an
ADO Recordset?
9. Can you give an example of what might be best suited to place in
the Application_Start and Session_Start subroutines?
10. If I'm developing an application that must accomodate multiple
security levels though secure login and my ASP.NET web appplication is
spanned across three web-servers (using round-robbin load balancing)
what would be the best approach to maintain login-in state for the
11. What are ASP.NET Web Forms? How is this technology different than
what is available though ASP (1.0-3.0)?
12. How does VB.NET/C# achieve polymorphism?
11. Can you explain what inheritance is and an example of when you
might use it?
13. How would you implement inheritance using VB.NET/C#?
14. Whats an assembly
15. Describe the difference between inline and code behind - which is
best in a
16. loosely coupled solution
17. Explain what a diffgram is, and a good use for one
18. Where would you use an iHTTPModule, and what are the limitations
of any
19. approach you might take in implementing one
20. What are the disadvantages of viewstate/what are the benefits
21 Describe session handling in a webfarm, how does it work and what
are the > limits
22. How would you get ASP.NET running in Apache web servers - why
would you even do this?
23. Whats MSIL, and why should my developers need an appreciation of
it if at all?
24. In what order do the events of an ASPX page execute. As a
developer is it important to undertsand these events?
25. Which method do you invoke on the DataAdapter control to load your
generated dataset with data?
26. Can you edit data in the Repeater control?
27. Which template must you provide, in order to display data in a
Repeater control?
28. How can you provide an alternating color scheme in a Repeater
29. What property must you set, and what method must you call in your
code, in order to bind the data from some data source to the Repeater
30. What base class do all Web Forms inherit from?
31. What method do you use to explicitly kill a user s session?
32 How do you turn off cookies for one page in your site?
33. Which two properties are on every validation control?
34. What tags do you need to add within the asp:datagrid tags to bind
columns manually?
35. How do you create a permanent cookie?
36. What tag do you use to add a hyperlink column to the DataGrid?
37. What is the standard you use to wrap up a call to a Web service
38. Which method do you use to redirect the user to another page
without performing a round trip to the client?
39. What is the transport protocol you use to call a Web service SOAP
40. True or False: A Web service can only be written in .NET
41. What does WSDL stand for?
42. What property do you have to set to tell the grid which page to go
to when using the Pager object?
43. Where on the Internet would you look for Web services?
44. What tags do you need to add within the asp:datagrid tags to bind
columns manually.
45. Which property on a Combo Box do you set with a column name, prior to setting the DataSource, to display data in the combo box?
46. How is a property designated as read-only?
47. Which control would you use if you needed to make sure the values
in two different controls matched?
48. True or False: To test a Web service you must create a windows
application or Web application to consume this service?
49. How many classes can a single .NET DLL contain?

- What are HTML controls, Web controls, and server controls.
- Briefly explain how the server control validation controls work.
- Briefly explain what user controls are and what server controls are and
the differences between the two.
- Briefly explain how server form post-back works (perhaps ask about view state as well).
- Can the action attribute of a server-side form tag be set to a value and if not how can you possibly pass data from a form page to a subsequent page. (Extra credit: Have you heard of comdna. :-)
- Briefly describe the role of global.asax.
- How would ASP and ASP.NET apps run at the same time on the same server?
- What are good ADO.NET object(s) to replace the ADO Recordset object.
Seems like some pretty tough questions for an interview (and certainly
questions like the ones above should not be the only type asked at an
interview) but it's a tough job market out there, a lot of people claim to
have a lot of experience with ASP.NET but have really just installed Beta 1 and maybe Beta 2 and played around for a week, and something like the above should give a quick sense as to whether someone has hands-on with ASP.NET or not.
return binaryFormatter.Deserialize(stream);

A foreground thread runs indefinitely, while a background thread terminates once the last foreground thread has stopped. You can use the IsBackground property to determine or change the background status of a thread. Note, this is not the same as thread priority which determines the allocation of processor time based on the priorities of the running threads.

Structs vs Class:

Val Calls
a.Name = Andrew
b.Name = James
Ref Calls
a.Name = James
b.Name = James

The output of the example shows that only the value of the class field was changed when passing the parameters by value. The struct field, did not change since a COPY of the struct is passed to the method (rather than a reference to the class). When the methods are called by ref, both values change since the struct no longer gets copied.


a) No.
b) No.
c) No.
d) Yes, eg:

interface IImage
void Paint();

struct Picture : IImage
public void Paint()
// painting code goes here
private int x, y, z; // other struct members

A25. Finalizers

a) When an object with a finalizer is collected, it's not immediately removed from memory. Instead, a reference to the object is placed in a special finalization queue. A dedicated finalization thread then calls the finalizer and then marks the object as no longer requiring finalization before removing it from the finalization queue. Until finalization is complete, the queue's reference to the object is sufficent to keep the object alive. After finalization the object will be reclaimed during the next garbage collection.

When an object is finalized, other objects that it refers to may have already been finalized. During finalization, you can safely free external resources such as operating system handles or database connections, but objects on the managed heap SHOULD NOT BE REFERENCED.

b) Avoid creating finalizers whenever possible. Objects with finalizers are more costly as they maintain their existance through at least two garbage collection passes. Finalizers should only be used for disposing on unmanaged handles or other such resources.

c) Finalizers should always be declared as protected. Never expose a finalizer.

d) The code should look something like the block below. Note, the GC.SuppressFinalize which prevents the finalizer
being called if the client has correctly called the Dispose method.

public class DemoFileHandleClass: IDisposable
IntPtr handleToSomeResource;

/// Object finaliser


/// Disposes of objects resources

public void Dispose()

/// Protected dispose method, handles releasing resources.

protected void Dispose(bool disposing)
if ( disposing )
// Object has been correctly disposed of,
// prevent finalizer from being called
// Dispose of mananged objects here
// Release unmanaged/external resources

e) The GC.SuppressFinalize() method prevents a finalizer from being called. You would normally do this in the Dispose method of an object that implements the IDisposable interface. Once the Dispose method has been explicitly called and has released all relevant resources you generally no longer need the garbage collector to call Object.Finalize.

A 26. Arrays

a) Are rectangular array has consistent array dimensions whereas jagged arrays have varying length dimensions.
b) 3d rectangular array:
string[,,] userNames;

3d jagged array:
string[][][] userNames;

c) It performs a shallow copy, i.e. any reference types that are in the array are not copied.

A 27. Value Type

public struct Andrew
private int _age;

/// Overload the equality operator (tests the ages are the same).

/// True if objects are the same age.
public static bool operator ==(Andrew a, Andrew b)
return a.Age == b.Age;

/// Overload the equality operator (tests the age is

/// True if objects are the same age.
public static bool operator !=(Andrew a, Andrew b)
return a.Age != b.Age;

/// Overrides the Object.Equals method.

/// Returns true if the objects are the same
/// or their ages are the same.

public override bool Equals(object obj)
bool result = false;
if ( obj != null )
if ( (object)this == obj )
// References are the same
result = true;
if ( obj is Andrew )
// Test if the ages are the same
return ((Andrew)obj).Age == this.Age;
return result;

/// Gets or sets the age of an object.

public int Age
get{ return _age; }
set{ _age = value; }

/// Return the hash code

public override int GetHashCode()
return _age;

A 28. Explicit Interfaces

a) No the class will not compile as the interface has the "public" modifier infront of it.
b) You use explicit interfaces when don't want the interface calls to accessible via the type that impliments it.

A 29. Dates

/// Returns the quarter for the the week supplied (i.e. the Friday).

/// The date to return the quarter for.
/// An integer value between 1 and 4 representing the quarter for the supplied date.
public static int GetQuarter(DateTime date)
return System.Convert.ToInt32(Math.Ceiling(date.Month / 3d));

The function should look something like the above code. Note that you need to append the number 3 with a "d" character to force the calculation to return a double. The candiate could also use a simple switch statement, but this is a less optimal answer.

A 30. Iterators

Example iterating through a collection using GetEnumerator.
There is no difference between using GetEnumerator() and writing a foreach loop, they compile to the same instructions.

// Create a string dictonary
StringDictionary myDictonary = new StringDictionary();
myDictonary.Add("User1","Andrew Baker");
myDictonary.Add("User2","David Beckham");

Console.WriteLine("METHOD A");
// Iterate through the dictonary using IEnumerator
IEnumerator iEnum = myDictonary.GetEnumerator();

// Cast the current value to a dictionary entry
DictionaryEntry de = (DictionaryEntry)iEnum.Current;
Console.WriteLine("Key: {0}, Value: {1}.", de.Key, de.Value);

Console.WriteLine("METHOD B");
// Iterate through the dictonary using IDictionaryEnumerator
IDictionaryEnumerator idictEnum = (IDictionaryEnumerator)myDictonary.GetEnumerator();

Console.WriteLine("Key: {0}, Value: {1}.", idictEnum.Key, idictEnum.Value);

A 31. IDisposable

[DateTime.Now]. Message TEST 3. Dispose Called

None of the other two Dispose methods will get called. In the first instance an exception is throw before the call to Dispose and in the second instance setting an object to null will not result in Dispose being called.

A 32. Value and Reference Type

a) This will output the value 10, because an implicit boxing operation occurs in the assignment of p to refPoint which causes the value of p to be copied. Had the Point struct been declared as a class the value 20 would be returned, because p and refPoint would reference to the same instance on the heap.

This process is known as boxing (unboxing is the opposite).


// Wil return True as same value
Console.WriteLine( "Test 1: " + (a == b) );

// Will return true as the call will be delegated to the string equals comparison
Console.WriteLine( "Test 2: " + Object.Equals( a, b) );

// Will return False as they are boxes into different objects
Console.WriteLine( "Test 3: " + ((object)a == (object)b) );

// Will return True. Even though they are seemingly two different reference types
// the literal string "hello" is interned by the compiler. So both references will
// point to an interned instance of "hello" (look at String.IsInterned for documentation).
Console.WriteLine( "Test 4: " + Object.ReferenceEquals(a, c) );

// Will return true as the same value
Console.WriteLine( "Test 5: " + (c == a) );

// Will return true as d is take from the interned pool
Console.WriteLine( "Test 6: " + Object.ReferenceEquals(a, d) );

Note, although string is a reference type the equality operators (== and !=) are defined to compare the values of string objects, not references. This was designed to make testing for string equality more intuitive.

A 33. Reference to a Value type

This is not possible. C# won't let you get the reference to a value because of the presence of the garbage collector. If you had a reference (aka internal pointer) somewhere into the middle of an array, any movement of the array as part of a GC would mean that the reference would be invalid. Hence any referencing of value types results in a copy.

You can however do this using unsafe code:

class UnsafePointerExample
/// The main entry point for the application.

static void Main(string[] args)
TestStruct t = new TestStruct();

TestStruct* pt1 = &t;
TestStruct* pt2 = &t;

// Set the value of pt1 to 100
pt1->x = 100;

// Print the value of pt1
Console.WriteLine(pt1->x); // prints 100
// Print the value of pt2
Console.WriteLine(pt2->x); // prints 100
// Print the value of the actual struct
Console.WriteLine(t.x); // prints 100


public struct TestStruct
public int x;
public int y;

A 34. Basic Maths

a) If you got 5000 you are wrong, the correct answer is 4100.
b) 323.

A 35. Logic

a) If you answered that you are first, then you are
wrong. If you overtake the second person and you take his
place, so you are second.

b) If you answered that you are second to last, then you are
wrong. It is impossible overtake the LAST Person, unless you count lapping them
(in which case you will remain in the same position that you were before
you lapped them).

A 36. Case Statements

a) Compiles and writes the number to the console window.
b) Does not compile. Although C# does supports fall through cases it does not support falling out of one case block into another.
c) Uses an explicit transfer which behaves identically to case a).

A 37. Basic Delegates

The delegate definition should look like:

/// Delegate to call CallOnMe.MyFunction

public delegate string CallMyFunctionHandler(string myValue);

The code to call the delegate should look like:

// Define an instance of the delegate
CallMyFunction callFunct = new CallMyFunction( new CallOnMe().MyFunction );
// Invoke the delegate
Console.WriteLine( callFunct.DynamicInvoke( new object[]{"My Test Call"} ) );

A 38. Basic Database and ADO Questions

a) It returns a read-only, forward-only rowset from the data source. A DataReader provides fast access when a forward-only sequential read is needed.
b) Multiple processes must agree that they will share the same connections, where every parameter is the same, including the security settings. The connection string must be identical.

A 39. ASP.NET Basics

a) Server-side code executes on the server. Client-side code executes in the context of the clients' browser.
b) Session objects, Application objects, ViewState, cookies, hidden form fields.
c) It allows page objects to save their state in a Base64 encoded string in the page HTML. One should only have it enabled when needed because it adds to the page size and can get fairly large for complex pages with many controls. (It takes longer to download the page).
d) Server.Transfer transfers execution directly to another page. Response. Redirect sends a response to the client and directs the client (the browser) to load the new page (it causes a roundtrip). If you don't need to execute code on the client, Transfer is more efficient.
e) Use a State Server or SQL Server to store the session state.
f) The Page class.
g) (Web Services Description Language). It describes the interfaces and other information of a web service.
h) CompareValidator Control
i) You must set the DataSource property and call the DataBind method.

A 40. Architecture

a) N-Tier model answer should include:

1. Presentation (UI).
2. Business (logic and underlying code) .
3. Data (from storage or other sources).

b) Commonly used Microsoft Application Blocks are (note, there are others):

Exception Management
Data Access
User Interface
Caching Application Block for .NET
Asynchronous Invocation Application Block for .NET
Configuration Management Application Block for .NET

A 41. Basic Locking

a) Both synchronization techniques shown require the callee to explicitly apply locks in order to prevent simultaneous multithreaded access to their underlying collections.

b) Neither provide guaranteed method level locking (see a).

c) The code to create a synchronised hashtable is:

Hashtable hashSync = Hashtable.Synchronized( new Hashtable() );

Doing this removes the needs for locks when adding or removing, since the called collection now handles each call to it. However, even when a collection is synchronized, other threads could still modify the items in it, which will cause any enumerators to throw exceptions. To guarantee thread safety during enumeration you must use a lock.

d) In summary SyncRoot is rarely useful, see for details.

A 42. Interfaces

Yes the code does compile. The code needed to return the string "Driving my car home" is:

IPersonalCar myCar = new MyCar();
string strReturn = myCar.Drive();

A 43. Interfaces Members

e. Events

A 44. Static Constructors

c. A static constructor is called before the first instance of the class is created, or before the first static method is called.

A 45. Operators

The code will return the following:

1 False
2 True
3 True
4 True
5 True

The first result results false, since this tests checks the reference equality of two boxed parameters. All the other tests check for value equality.

A 46. Operators

You cannot overload the && or || operators, but you can affect how they are evaluated. When the && or || operators are called the C# compiler generates code which calls the true, false and & operators. Overloading these will enable you to customise the behaviour of these operators.

A 47. Remoting

a) Remoting is a more efficient communication exchange when you can control both ends of the application involved in the communication process. Web Services provide an open-protocol-based exchange of informaion. Web Services are best when you need to communicate with an external organization or another (non-.NET) technology.

b) Remotable objects are the objects that can be marshaled across the application domains. You can marshal by value, where a deep copy of the object is created and then passed to the receiver. You can also marshal by reference, where just a reference to an existing object is passed.

c) If the server object is instantiated for responding to just one single request, the request should be made in SingleCall mode.

d) A single object is instantiated regardless of the number of clients accessing it. Lifetime of this object is determined by lifetime lease.

e) By implementing ILease interface when writing the class code.

f) Channels represent the objects that transfer the other serialized objects from one application domain to another and from one computer to another, as well as one process to another on the same box. A channel must exist before an object can be transferred.

A 48. Architecture

Cyclomatic complexity is the most widely used member of a class of static software metrics. Cyclomatic complexity may be considered a broad measure of soundness and confidence for a program. Introduced by Thomas McCabe in 1976, it measures the number of linearly-independent paths through a program module. This measure provides a single ordinal number that can be compared to the complexity of other programs. Cyclomatic complexity is often referred to simply as program complexity, or as McCabe's complexity. It is often used in concert with other software metrics. As one of the more widely-accepted software metrics, it is intended to be independent of language and language format.

A large number of programs have been measured, and ranges of complexity have been established that help the software engineer determine a program's inherent risk and stability. The resulting calibrated measure can be used in development, maintenance, and reengineering situations to develop estimates of risk, cost, or program stability. Studies show a correlation between a program's cyclomatic complexity and its error frequency. A low cyclomatic complexity contributes to a program's understandability and indicates it is amenable to modification at lower risk than a more complex program. A module's cyclomatic complexity is also a strong indicator of its testability (see Test planning under Usage Considerations).

Risk Evaluation

1-10 A simple program, without much risk.
11-20 More complex, moderate risk.
21-50 Complex, high risk program
> 50 Untestable program (very high risk)

A 49. Security Attributes

All the relevant information is stored in the asssembly metadata on compilation and based on permissions of the calling code. The CLR will make sure that application or assembly doesn't even get loaded in cases where the callee doesn't have relevant permissions vis a vis Imperative security, where everything is checked in assembly code and assembly will invariably get loaded and executed before it checks for any such issue or lack of permissions.

So , benefits of Declarative security are:

1. Inducing efficiency as all relevant information is stored in the metadata.
2. Cleaner code as security is not mixed with program logic it's done cleanly using attributes.

A 50. Native Image Cache

A native image is a file containing compiled processor-specific machine code. The native image cache is a reserved area of the global assembly cache. Once you create a native image for an assembly, the runtime automatically uses that native image each time it runs the assembly. You do not have to perform any additional procedures to cause the runtime to use a native image. Running Ngen.exe on an assembly allows the assembly to load and execute faster, because it restores code and data structures from the native image cache rather than generating them dynamically using the IL.

Topic Notes:

The JIT compiler knows precisely which CPU the user has installed in their computer causing the JIT compiler to produce native instructions that are specific to the user's machine. When you use an unmanaged compiler, the compiler usually emits code for an Intel Pentium Pro, Pentium II, Pentium III, or Pentium 4 processor.

The JIT compiler knows if the machine has a single CPU or multiple CPUs installed. If a single CPU is installed, certain thread synchronization mechanisms don't have to be employed.

When a method is JIT compiled, the compiler emits the native CPU instructions. Some of these instructions contain memory addresses that refer to variables or methods. By contrast, an unmanaged compiler and linker emit native CPU instructions that contain memory addresses when building the resulting file. This file must contain relocation information; if Windows can't load the file at its preferred base address, then the embedded memory addresses are incorrect and they must be fixed-up by the Windows' loader. Dynamic relocation (rebasing) significantly hurts the load time of unmanaged code.

The native image that Ngen.exe generates cannot be shared across Application Domains. Therefore, you cannot use Ngen.exe in application scenarios, such as ASP.NET, that require assemblies to be shared across application domains.

No Intellectual Property Protection. Many people believe that it might be possible to ship NGen'd files without shipping the files containing the original IL code thereby keeping their intellectual property a secret. Unfortunately, this is not possible. At runtime, the CLR requires access to the assembly's metadata and the NGen'd files do not contain the metadata.

NGen'd Files Can Get Out-Of-Sync. When the CLR loads an NGen'd file it compares a number of attributes about the previously-compile code and the current execution environment. If any of the attributes don't match then the NGen'd file cannot be used and the normal JIT compiler process is used instead.

Poor Administration. NGen'd file are not automatically deleted when an assembly is uninstalled adversely affecting the .NET Framework's easy administration and XCOPY deployment story.

Inferior Load-Time Performance (Rebasing). When Windows loads an NGen'd file, it checks to see if the file loads at its preferred base address. If the file can't load at its preferred base address, then Windows relocates the file, fixing-up all of the memory address references. This is time consuming because Windows must load the entire file into memory and modify various bytes within the file. If you NGen your assemblies it is recommended you explicitly set the base addresses.

For server side applications NGen.exe makes no sense, since only the first client request experiences a performance hit; future client requests run at normal speed.

A 51. Shallow Copy, Deep Copy and MemberWiseClone

A shallow copy creates a new instance of the same type as the original object, and then copies the nonstatic fields of the original object. If the field is a value type, a bit-by-bit copy of the field is performed. If the field is a reference type, the reference is copied but the referred object is not; therefore, the reference in the original object and the reference in the clone point to the same object. In contrast, a deep copy of an object duplicates everything directly or indirectly referenced by the fields in the object.

MemberwiseClone method, creates a new instance of the source object and then does a bit-by-bit copy of value types. For reference types, only the reference is copied. As a result both the original object and the clone end-up pointing to the same objects that the original object refers.

For example, if X is an object and it references objects Y and Z then a shallow copy A of X will still reference the same Y and Z objects.

A 52.

This code returns 0 (zero), since the first line of code carries out an integer division which will round down to zero. To perform the calculation as a double do the following:

// Use the "d" type marker to denote the values as doubles
double expectedValue = 1d/2d;
if ( expectedValue > 0 )
expectedValue = expectedValue + 0.5;

1. What’s the advantage of using System.Text.StringBuilder over System.String? StringBuilder is more efficient in the cases, where a lot of manipulation is done to the text. Strings are immutable, so each time it’s being operated on, a new instance is created.
2. Can you store multiple data types in System.Array? No.
3. What’s the difference between the System.Array.CopyTo() and System.Array.Clone()? The first one performs a deep copy of the array, the second one is shallow.
4. How can you sort the elements of the array in descending order? By calling Sort() and then Reverse() methods.
5. What’s the .NET datatype that allows the retrieval of data by a unique key? HashTable.
6. What’s class SortedList underneath? A sorted HashTable.
7. Will finally block get executed if the exception had not occurred? Yes.
8. What’s the C# equivalent of C++ catch (…), which was a catch-all statement for any possible exception? A catch block that catches the exception of type System.Exception. You can also omit the parameter data type in this case and just write catch {}.
9. Can multiple catch blocks be executed? No, once the proper catch code fires off, the control is transferred to the finally block (if there are any), and then whatever follows the finally block.
10. Why is it a bad idea to throw your own exceptions? Well, if at that point you know that an error has occurred, then why not write the proper code to handle that error instead of passing a new Exception object to the catch block? Throwing your own exceptions signifies some design flaws in the project.
11. What’s a delegate? A delegate object encapsulates a reference to a method. In C++ they were referred to as function pointers.
12. What’s a multicast delegate? It’s a delegate that points to and eventually fires off several methods.
13. How’s 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.
14. What are the ways to deploy an assembly? An MSI installer, a CAB archive, and XCOPY command.
15. What’s 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.
16. What namespaces are necessary to create a localized application? System.Globalization, System.Resources.
17. What’s the difference between // comments, /* */ comments and /// comments? Single-line, multi-line and XML documentation comments.
18. How do you generate documentation from the C# file commented properly with a command-line compiler? Compile it with a /doc switch.
19. What’s the difference between and XML documentation tag? Single line code example and multiple-line code example.
20. Is XML case-sensitive? Yes, so and are different elements.
21. What debugging tools come with the .NET SDK? CorDBG – command-line debugger, and DbgCLR – graphic debugger. Visual Studio .NET uses the DbgCLR. To use CorDbg, you must compile the original C# file using the /debug switch.
22. What does the This window show in the debugger? It points to the object that’s pointed to by this reference. Object’s instance data is shown.
23. What does assert() 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.
24. What’s the difference between the Debug class and Trace class? Documentation looks the same. Use Debug class for debug builds, use Trace class for both debug and release builds.
25. Why are there five tracing levels in System.Diagnostics.TraceSwitcher? The tracing dumps can be quite verbose and for some applications that are constantly running you run the risk of overloading the machine and the hard drive there. Five levels range from None to Verbose, allowing to fine-tune the tracing activities.
26. Where is the output of TextWriterTraceListener redirected? To the Console or a text file depending on the parameter passed to the constructor.
27. How do you debug an ASP.NET Web application? Attach the aspnet_wp.exe process to the DbgClr debugger.
28. What are three test cases you should go through in unit testing? Positive test cases (correct data, correct output), negative test cases (broken or missing data, proper handling), exception test cases (exceptions are thrown and caught properly).
29. Can you change the value of a variable while debugging a C# application? Yes, if you are debugging via Visual Studio.NET, just go to Immediate window.
30. Explain the three services model (three-tier application). Presentation (UI), business (logic and underlying code) and data (from storage or other sources).
31. What are advantages and disadvantages of Microsoft-provided data provider classes in ADO.NET? SQLServer.NET data provider is high-speed and robust, but requires SQL Server license purchased from Microsoft. OLE-DB.NET is universal for accessing other sources, like Oracle, DB2, Microsoft Access and Informix, but it’s a .NET layer on top of OLE layer, so not the fastest thing in the world. ODBC.NET is a deprecated layer provided for backward compatibility to ODBC engines.
32. What’s the role of the DataReader class in ADO.NET connections? It returns a read-only dataset from the data source when the command is executed.
33. What is the wildcard character in SQL? Let’s say you want to query database with LIKE for all employees whose name starts with La. The wildcard character is %, the proper query with LIKE would involve ‘La%’.
34. Explain ACID rule of thumb for transactions. Transaction must be Atomic (it is one unit of work and does not dependent on previous and following transactions), Consistent (data is either committed or roll back, no “in-between” case where something has been updated and something hasn’t), Isolated (no transaction sees the intermediate results of the current transaction), Durable (the values persist if the data had been committed even if the system crashes right after).
35. What connections does Microsoft SQL Server support? Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and passwords).
36. Which one is trusted and which one is untrusted? Windows Authentication is trusted because the username and password are checked with the Active Directory, the SQL Server authentication is untrusted, since SQL Server is the only verifier participating in the transaction.
37. Why would you use untrusted verificaion? Web Services might use it, as well as non-Windows applications.
38. What does the parameter Initial Catalog define inside Connection String? The database name to connect to.
39. What’s the data provider name to connect to Access database? Microsoft.Access.
40. What does Dispose method do with the connection object? Deletes it from the memory.
41. What is a pre-requisite for connection pooling? Multiple processes must agree that they will share the same connection, where every parameter is the same, including the security settings.

ASP interview questions
Used by IBM Consulting Services, according to the site visitor.
1. How many objects are there in ASP?
2. Which DLL file is needed to be registered for ASP?
3. If you want to initialize a global variable for an application, which is the right place to declare it? (like form or some other file).
4. What is diffrence between Server.transfer and Response.redirect.
5. Is there any inbuilt paging(for example shoping cart. which will show next 10 records without refreshing) in ASP? How will you do pating.
6. What does Server.MapPath do?
7. Name at least three methods of response object other than Redirect.
8. Name at least two methods of response object other than Transfer.
9. Tell few programming diffrence between ADO and DAO programming. What is state?
10. How many types of cookies are there?
11. Tell few steps for optimizing (for speed and resources) ASP page/application

C# .NET interview questions
Good for preparation and general self-testing, but too specific for the actual job interview. This was sent in by a job applicant getting ready to step into the .NET field in India.
1. Are private class-level variables inherited? - Yes, but they are not accessible, so looking at it you can honestly say that they are not inherited. But they are.
2. Why does DllImport not work for me? - All methods marked with the DllImport attribute must be marked as public static extern.
3. Why does my Windows application pop up a console window every time I run it? - Make sure that the target type set in the project properties setting is set to Windows Application, and not Console Application. If you’re using the command line, compile with /target:winexe, not /target:exe.
4. Why do I get an error (CS1006) when trying to declare a method without specifying a return type? - If you leave off the return type on a method declaration, the compiler thinks you are trying to declare a constructor. So if you are trying to declare a method that returns nothing, use void. The following is an example: // This results in a CS1006 error public static staticMethod (mainStatic obj) // This will work as wanted public static void staticMethod (mainStatic obj)
5. Why do I get a syntax error when trying to declare a variable called checked? - The word checked is a keyword in C#.
6. Why do I get a security exception when I try to run my C# app? - Some security exceptions are thrown if you are working on a network share. There are some parts of the frameworks that will not run if being run off a share (roaming profile, mapped drives, etc.). To see if this is what’s happening, just move the executable over to your local drive and see if it runs without the exceptions. One of the common exceptions thrown under these conditions is System.Security.SecurityException. To get around this, you can change your security policy for the intranet zone, code group 1.2, (the zone that running off shared folders falls into) by using the caspol.exe tool.
7. Why do I get a CS5001: does not have an entry point defined error when compiling? - The most common problem is that you used a lowercase ‘m’ when defining the Main method. The correct way to implement the entry point is as follows: class test { static void Main(string[] args) {} }
8. What optimizations does the C# compiler perform when you use the /optimize+ compiler option? - The following is a response from a developer on the C# compiler team: We get rid of unused locals (i.e., locals that are never read, even if assigned). We get rid of unreachable code. We get rid of try-catch with an empty try. We get rid of try-finally with an empty try. We get rid of try-finally with an empty finally. We optimize branches over branches: gotoif A, lab1 goto lab2: lab1: turns into: gotoif !A, lab2 lab1: We optimize branches to ret, branches to next instruction, and branches to branches.
9. What is the syntax for calling an overloaded constructor within a constructor (this() and constructorname() does not compile)? - The syntax for calling another constructor is as follows: class B { B(int i) { } } class C : B { C() : base(5) // call base constructor B(5) { } C(int i) : this() // call C() { } public static void Main() {} }
10. What is the equivalent to regsvr32 and regsvr32 /u a file in .NET development? - Try using RegAsm.exe. Search MSDN on Assembly Registration Tool.
11. What is the difference between a struct and a class in C#? - From language spec: The list of similarities between classes and structs is as follows. Longstructs can implement interfaces and can have the same kinds of members as classes. Structs differ from classes in several important ways; however, structs are value types rather than reference types, and inheritance is not supported for structs. Struct values are stored on the stack or in-line. Careful programmers can sometimes enhance performance through judicious use of structs. For example, the use of a struct rather than a class for a Point can make a large difference in the number of memory allocations performed at runtime. The program below creates and initializes an array of 100 points. With Point implemented as a class, 101 separate objects are instantiated-one for the array and one each for the 100 elements.
12. My switch statement works differently than in C++! Why? - C# does not support an explicit fall through for case blocks. The following code is not legal and will not compile in C#:
13. switch(x)
14. {
15. case 0: // do something
16. case 1: // do something as continuation of case 0
17. default: // do something in common with
18. //0, 1 and everything else
19. break;
20. }
To achieve the same effect in C#, the code must be modified as shown below (notice how the control flows are explicit):
class Test
public static void Main() {
int x = 3;
case 0: // do something
goto case 1;
case 1: // do something in common with 0
goto default;
default: // do something in common with 0, 1, and anything else
21. Is there regular expression (regex) support available to C# developers? - Yes. The .NET class libraries provide support for regular expressions. Look at the System.Text.RegularExpressions namespace.
22. Is there any sample C# code for simple threading? - Yes:
23. using System;
24. using System.Threading;
25. class ThreadTest
26. {
27. public void runme()
28. {
29. Console.WriteLine(\"Runme Called\");
30. }
31. public static void Main(String[] args)
32. {
33. ThreadTest b = new ThreadTest();
34. Thread t = new Thread(new ThreadStart(b.runme));
35. t.Start();
36. }
37. Is there an equivalent of exit() for quitting a C# .NET application? - Yes, you can use System.Environment.Exit(int exitCode) to exit the application or Application.Exit() if it’s a Windows Forms app.
38. Is there a way to force garbage collection? - Yes. Set all references to null and then call System.GC.Collect(). If you need to have some objects destructed, and System.GC.Collect() doesn’t seem to be doing it for you, you can force finalizers to be run by setting all the references to the object to null and then calling System.GC.RunFinalizers().
39. Is there a way of specifying which block or loop to break out of when working with nested loops? - The easiest way is to use goto:
40. using System;
41. class BreakExample
42. {
43. public static void Main(String[] args) {
44. for(int i=0; i<3; i++)
45. {
46. Console.WriteLine(\"Pass {0}: \", i);
47. for( int j=0 ; j<100 ; j++ )
48. {
49. if ( j == 10)
50. goto done;
51. Console.WriteLine(\"{0} \", j);
52. }
53. Console.WriteLine(\"This will not print\");
54. }
55. done:
56. Console.WriteLine(\"Loops complete.\");
57. }
58. Is it possible to restrict the scope of a field/method of a class to the classes in the same namespace? - There is no way to restrict to a namespace. Namespaces are never units of protection. But if you’re using assemblies, you can use the ‘internal’ access modifier to restrict access to only within the assembly.

Interview questions for C# developers
Useful for preparation, but too specific to be used in the interview.
1. Is it possible to inline assembly or IL in C# code? - No.
2. Is it possible to have different access modifiers on the get/set methods of a property? - No. The access modifier on a property applies to both its get and set accessors. What you need to do if you want them to be different is make the property read-only (by only providing a get accessor) and create a private/internal set method that is separate from the property.
3. Is it possible to have a static indexer in C#? - No. Static indexers are not allowed in C#.
4. If I return out of a try/finally in C#, does the code in the finally-clause run? - Yes. The code in the finally always runs. If you return out of the try block, or even if you do a “goto” out of the try, the finally block always runs:
5. using System;
7. class main
8. {
9. public static void Main()
10. {
11. try
12. {
13. Console.WriteLine(\"In Try block\");
14. return;
15. }
16. finally
17. {
18. Console.WriteLine(\"In Finally block\");
19. }
20. }
Both “In Try block” and “In Finally block” will be displayed. Whether the return is in the try block or after the try-finally block, performance is not affected either way. The compiler treats it as if the return were outside the try block anyway. If it’s a return without an expression (as it is above), the IL emitted is identical whether the return is inside or outside of the try. If the return has an expression, there’s an extra store/load of the value of the expression (since it has to be computed within the try block).
21. I was trying to use an “out int” parameter in one of my functions. How should I declare the variable that I am passing to it? - You should declare the variable as an int, but when you pass it in you must specify it as ‘out’, like the following: int i; foo(out i); where foo is declared as follows: [return-type] foo(out int o) { }
22. How does one compare strings in C#? - In the past, you had to call .ToString() on the strings when using the == or != operators to compare the strings’ values. That will still work, but the C# compiler now automatically compares the values instead of the references when the == or != operators are used on string types. If you actually do want to compare references, it can be done as follows: if ((object) str1 == (object) str2) { … } Here’s an example showing how string compares work:
23. using System;
24. public class StringTest
25. {
26. public static void Main(string[] args)
27. {
28. Object nullObj = null; Object realObj = new StringTest();
29. int i = 10;
30. Console.WriteLine(\"Null Object is [\" + nullObj + \"]\n\"
31. + \"Real Object is [\" + realObj + \"]\n\"
32. + \"i is [\" + i + \"]\n\");
33. // Show string equality operators
34. string str1 = \"foo\";
35. string str2 = \"bar\";
36. string str3 = \"bar\";
37. Console.WriteLine(\"{0} == {1} ? {2}\", str1, str2, str1 == str2 );
38. Console.WriteLine(\"{0} == {1} ? {2}\", str2, str3, str2 == str3 );
39. }
40. }
Null Object is []
Real Object is [StringTest]
i is [10]
foo == bar ? False
bar == bar ? True
41. How do you specify a custom attribute for the entire assembly (rather than for a class)? - Global attributes must appear after any top-level using clauses and before the first type or namespace declarations. An example of this is as follows:
42. using System;
43. [assembly : MyAttributeClass] class X {}
Note that in an IDE-created project, by convention, these attributes are placed in AssemblyInfo.cs.
44. How do you mark a method obsolete? -
[Obsolete] public int Foo() {...}
[Obsolete(\"This is a message describing why this method is obsolete\")] public int Foo() {...}
Note: The O in Obsolete is always capitalized.
45. How do you implement thread synchronization (Object.Wait, Notify,and CriticalSection) in C#? - You want the lock statement, which is the same as Monitor Enter/Exit:
46. lock(obj) { // code }
translates to
try {
// code
47. How do you directly call a native function exported from a DLL? - Here’s a quick example of the DllImport attribute in action:
48. using System.Runtime.InteropServices; 49. class C
50. {
51. [DllImport(\"user32.dll\")]
52. public static extern int MessageBoxA(int h, string m, string c, int type);
53. public static int Main()
54. {
55. return MessageBoxA(0, \"Hello World!\", \"Caption\", 0);
56. }
57. }
This example shows the minimum requirements for declaring a C# method that is implemented in a native DLL. The method C.MessageBoxA() is declared with the static and external modifiers, and has the DllImport attribute, which tells the compiler that the implementation comes from the user32.dll, using the default name of MessageBoxA. For more information, look at the Platform Invoke tutorial in the documentation.

58. How do I simulate optional parameters to COM calls? - You must use the Missing class and pass Missing.Value (in System.Reflection) for any values that have optional parameters.


Anonymous Anonymous said...

Thank you a lot for sharing this with all people you actually know what you're talking about! Bookmarked. Kindly

additionally seek advice from my website =). We

will have a hyperlink trade

arrangement among us!

my site :: restaurante ovni el campello

Thursday, April 25, 2013 5:38:00 AM  
Anonymous Anonymous said...

Excellent read, I just passed this onto a colleague
who was doing a little research on that. And he

just bought me lunch as I found it for him smile Thus
let me rephrase that:

Thanks for lunch!

my web page :: rural andalucia spain

Friday, April 26, 2013 5:49:00 AM  

Post a Comment

<< Home