Monday, January 21, 2008

.NET Interview Q&A

1. What is a static class?
Answer:
A static class is a class which can not be instantiated using the ‘new’ keyword. They also only contain static members, are sealed and have a private constructor.


2. What is static member?
Answer:
A static member is a method, field, property or event that can be called without creating an instance of its defining class. Static members are particularly useful for representing calculations and data that are independent of object state.


3. What is static function?
Answer:
A static function is another term for a static method. It allows you to execute the function without creating an instance of its defining class. They are similar to global functions. An example of a static function could be: ConvertFromFarenheitToCelsius with a signature as follows:

public static double ConvertFromFarenheitToCelsius (string valToConvert)
{ //add code here }


4. What is static constructor?
Answer:
A static constructor has a similar function as a normal constructor i.e. it is automatically called the first time a class is loaded. The differences between a conventional constructor are that it cannot be overloaded, cannot have any parameters nor have any access modifiers and must be preceded by the keyword static. In addition, a class with a static constructor may only have static members.


5. How can we inherit a static variable?
Answer:
When inheriting static members there is no need to instantiate the defining class using the ‘new’ keyword.

public class MyBaseClass
{
MyBaseClass() { }
public static void PrintName() { }
}

public class MyDerivedClass : MyBaseClass
{
MyDerivedClass () { }
public void DoSomething() { MyBaseClass.GetName(); }
}


6. What is different between Base Class Library (BCL) and Framework Class Library (FCL) in .NET?
Answer:
The Base Class Library (BCL), sometimes incorrectly referred to as the Framework Class Library (FCL) (which is a superset including the Microsoft.* namespaces), is a library of types available to all languages using the .NET Framework. The BCL provides classes which encapsulate a number of common functions such as file reading and writing, graphic rendering, database interaction, XML document manipulation, and so forth. The BCL is much larger than other libraries, but has much more functionality in one package.


7. Can we use a static function with a non-static variable?
Answer:
No.


8. How can we access static variable?
Answer:
By employing the use of a static member field as follows:
public class CashSales
{
//declare static member field
private static int maxUnitsAllowed = 50;

//declare method to return maximum number of units allowed

public static int GetMaxUnitsAllowed () { Return maxUnitsAllowed; }
}

The static field can now be accessed by simply doing CashSales.GetMaxUnitsAllowed(). No need to create an instance of the class.


9. Why main function is static?
Answer:
Because it is automatically loaded by the CLR and initialised by the runtime when the class is first loaded. If it wasn’t static an instance of the class would first need to be created and initialised.


10. How will you load dynamic assembly? How will create assemblies at run time?
Answer:
Load assembly:
By using classes from the System.Reflection namespace.
Assembly x = Assembly.LoadFrom( “LoadMe.dll” );

Create assembly:
Use classes from System.CodeDom.Compiler;


11. What is Reflection?
Answer:
The System.Reflection namespace provides us with a series of classes that allow us to interrogate the codebase at run-time and perform functions such as dynamically load assemblies, return property info e.t.c.


12. How do you create threading in.NET? What is the namespace for that?
Answer:
System.Threading;

//create new thread using the thread class’s constructor
Thread myThread = new Thread(new ThreadStart (someFunction));


13. What do you mean by Serialize?
Answer:
Serialization is the act of saving the state of an object so that it can be recreated (i.e deserialized) at a later date.


14. What is the difference between Array and LinkedList?
Answer:
An array is a collection of the same type. The size of the array is fixed in its declaration.
A linked list is similar to an array but it doesn’t have a limited size.


15. What is Asynchronous call and how it can be implemented using delegates?
Answer:
A synchronous call will wait for a method to complete before program flow is resumed. With an asynchronous call the program flow continues whilst the method executes.

//create object
SomeFunction objFunc = new SomeFunction();

//create delegate
SomeDelegate objDel = new SomeDelegate(objFunc.FunctionA);

//invoke the method asynchronously (use interface IAsyncResult)
IAsyncResult asynchCall = SomeDelegate.Invoke();


16. How to create events for a control? What is custom events? How to create it?
Answer:
An event is a mechanism used in a class that can be used to provide a notification when something interesting happens. (typical evens in a windows application include: change text in textbox, double click or click a button, select an item in dropdown box).

A custom event is an event created by the user that other developers can use. For example assuming that we have a CashTransaction class and we have a bank balance property in that class. We may want to set-up an event that provides a notification when the bank balance drops below a certain amount. In order to produce an event the process would be roughly as follows:
- Create the class for the event derived from EventArgs.
- Create a delegate with a return type of void.
- Create a class containing the method that will activate the event.
- Create a class with methods to handle the event.


17.
If you want to write your own .NET language, what steps you will you take care?
Answer:

We will need to ensure that the high level code is compiled to MSIL (Microsoft intermediate language) so that it can be interpreted by the CLR.


18. Describe the difference between inline and code behind - which is best in a loosely coupled solution?
Answer:
The term ‘code behind’ refers to application code that is not embedded within the ASPX page and is separated out into a separate file which is then referenced from the ASPX page. Inline code is the traditional ASP architectural model where business logic code was embedded within the ASP page. Separating the business logic code from the presentation layer offers several advantages:
a) It allows graphic designers and web developers to work on the presentation layer whilst the application developers concentrate on the business logic.
b) The codebehind file is compiled as a single dll increasing the efficiency of the application.
c) The codebehind model offers a true OO development platform.
d) It speeds up development time as it allows developers to fully maximise the features of the .NET framework such as Cahing, ViewState, Session, Smart Navigation etc.
e) Code is much easier to maintain and susceptible for change.
f) The compiler and VS.NET provides much better support for error checking, intellisense and debugging when using the code behind model.


19. Without modifying source code if we compile again, will it be generated MSIL again?
Answer:
No.


20. What are the new thee features of COM+ services, which are not there in COM (MTS)?
Answer:

- Role based security.
- Neutral apartment threading.
- New environment called context which defines the execution environment


21.
What are the differences between COM architecture and.NET architecture?
Answer:

- .Net architecture has superseded the old COM architecture providing a flexible rapid application development environment which can be used to create windows, web and console applications and web services.
- .NET provides a powerful development environment that can be used to create objects in any .NET compliant language.
- .NET addresses the previous problems of dll hell with COM by providing strongly named assemblies and side-by-side execution where two assemblies with the same name can run on the same box.


22. Can we copy a COM dll to GAC folder?
Answer:

No. It only stores .NET assemblies.


23. Can you explain what inheritance is and an example of when you might use it?
Answer:
Inheritance is a fundamental feature of any OO language. It allows us to inherit the members and attributes from a base class to a new derived class. This leads to increased code reusability and also makes applications easier to develop, maintain and extend as the new derived class can contain new features not available in the base class whilst at the same time preserving the attributes inherited from the base class.


24. What are virtual destructors?
Answer:
A constructor can not be virtual but a destructor may. Use virtual destructors when you want to implement polymorphic tearing down of an object.


25. What is close method? How it different from Finalize and Dispose?
Answer:
Finalize is the process that allows the garbage collector to clean up any unmanaged resources before it is destroyed.

The Finalize method can not be called directly; it is automatically called by the CLR. In order to allow more control over the release of unmanaged resources the .NET framework provides a dispose method which unlike finalise can be called directly by code.

Close method is same as dispose. It was added as a convenience.


26. What is Boxing and UnBoxing?
Answer:
Boxing is the process of converting a value type to a reference type. More specifically it involves encapsulating a copy of the object and moving it from stack to heap. Unboxing is the reverse process.


27. What is check/uncheck?
Answer:
- checked: used to enable overflow checking for arithmetic and conversion functions.
- unchecked: used to disable overflow checking for arithmetic and conversion functions.


28. What do you know about .NET assemblies?
Answer:
- Assemblies are the smallest units of versioning and deployment in the .NET application.
- Assemblies are also the building blocks for programs such as Web services, Windows services, serviced components, and .NET remoting applications.


29. What’s the difference between private and shared assembly?
Answer:
- Private assembly is used inside an application only and does not have to be identified by a strong name.
- Shared assembly can be used by multiple applications and has to have a strong name.


30. What’s a strong name?
Answer:
A strong name includes the name of the assembly, version number, culture identity, and a public key token.


31. How can you debug failed assembly binds?
Answer:
Use the Assembly Binding Log Viewer (fuslogvw.exe) to find out the paths searched.


32. Where are shared assemblies stored?
Answer:
Global assembly cache.


33. How can you create a strong name for a .NET assembly?
Answer:
With the help of Strong Name tool (sn.exe).


34. Where’s global assembly cache located on the system?
Answer:
Usually C:\winnt\assembly or C:\windows\assembly.


35. Can you have two files with the same file name in GAC?
Answer:
Yes, remember that GAC is a very special folder, and while normally you would not be able to place two files with the same name into a Windows folder, GAC differentiates by version number as well, so it’s possible for MyApp.dll and MyApp.dll to co-exist in GAC if the first one is version 1.0.0.0 and the second one is 1.1.0.0.


36. So let’s say I have an application that uses MyApp.dll assembly, version 1.0.0.0. There is a security bug in that assembly, and I publish the patch, issuing it under name MyApp.dll 1.1.0.0. How do I tell the client applications that are already installed to start using this new MyApp.dll?
Answer:
Use publisher policy. To configure a publisher policy, use the publisher policy configuration file, which uses a format similar app .config file. But unlike the app .config file, a publisher policy file needs to be compiled into an assembly and placed in the GAC.


37. What is delay signing?
Answer:

Delay signing allows you 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.


38.
What’s the advantage of using System.Text.StringBuilder over System.String?
Answer:
- 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.


39.
Can you store multiple data types in System.Array?
Answer:
No.


40.
What’s the difference between the System.Array.CopyTo() and System.Array.Clone()?
Answer:
The first one performs a deep copy of the array, the second one is shallow.


41.
How can you sort the elements of the array in descending order?
Answer:
By calling Sort() and then Reverse() methods.


42.
What’s the .NET datatype that allows the retrieval of data by a unique key?
Answer:
HashTable.


43.
What’s class SortedList underneath?
Answer:
A sorted HashTable.


44.
Will finally block get executed if the exception had not occurred?
Answer:
Yes.


45. What’s the C# equivalent of C++ catch (…), which was a catch-all statement for any possible exception?
Answer:
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 {}.


46.
Can multiple catch blocks be executed?
Answer:
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.


47.
Why is it a bad idea to throw your own exceptions?
Answer:
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.


48.
What’s a delegate?
Answer:
A delegate object encapsulates a reference to a method. In C++ they were referred to as function pointers.


49.
What’s a multicast delegate?
Answer:
It’s a delegate that points to and eventually fires off several methods.


50.
How’s the DLL Hell problem solved in .NET?
Answer:
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.


51.
What are the ways to deploy an assembly?
Answer:
An MSI installer, a CAB archive, and XCOPY command.


52.
What’s a satellite assembly?
Answer:
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.


53.
What namespaces are necessary to create a localized application?
Answer:
System.Globalization, System.Resources.


54.
What’s the difference between // comments, /* */ comments and /// comments?
Answer:
Single-line, multi-line and XML documentation comments.


55.
How do you generate documentation from the C# file commented properly with a command-line compiler?
Answer:
Compile it with a /doc switch.


56.
What’s the difference between [c> and [code> XML documentation tag?
Answer:
Single line code example and multiple-line code example.


57. Is XML case-sensitive?
Answer:
Yes, so [Student> and [student> are different elements.


58. What debugging tools come with the .NET SDK?
Answer:
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.


59.
What does the This window show in the debugger?
Answer:
It points to the object that’s pointed to by this reference. Object’s instance data is shown.


60.
What does assert() do?
Answer:
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.


61. What’s the difference between the Debug class and Trace class? Documentation looks the same.
Answer:
Use Debug class for debug builds, use Trace class for both debug and release builds.


62. Why are there five tracing levels in System.Diagnostics.TraceSwitcher?
Answer:
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.


63.
Where is the output of TextWriterTraceListener redirected?
Answer:
To the Console or a text file depending on the parameter passed to the constructor.


64.
How do you debug an ASP.NET Web application?
Answer:
Attach the aspnet_wp.exe process to the DbgClr debugger.


65.
What are three test cases you should go through in unit testing?
Answer:
- 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).


66.
Can you change the value of a variable while debugging a C# application?
Answer:
Yes, if you are debugging via Visual Studio.NET, just go to Immediate window.


67.
Explain the three services model (three-tier application).
Answer:
Presentation (UI), business (logic and underlying code) and data (from storage or other sources).


68. What are advantages and disadvantages of Microsoft-provided data provider classes in ADO.NET?
Answer:
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.


69.
What’s the role of the DataReader class in ADO.NET connections?
Answer:
It returns a read-only dataset from the data source when the command is executed.


70. 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.
Answer:
The wildcard character is %, the proper query with LIKE would involve ‘La%’.


71.
Explain ACID rule of thumb for transactions.
Answer:
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).


72.
What connections does Microsoft SQL Server support?
Answer:
Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and passwords).


73.
Which one is trusted and which one is untrusted?
Answer:
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.


74.
Why would you use untrusted verificaion?
Answer:
Web Services might use it, as well as non-Windows applications.


75.
What does the parameter Initial Catalog define inside Connection String?
Answer:
The database name to connect to.


76.
What’s the data provider name to connect to Access database?
Answer:
Microsoft.Access.


77.
What does Dispose method do with the connection object?
Answer:
Deletes it from the memory.


78.
What is a pre-requisite for connection pooling?
Answer:
Multiple processes must agree that they will share the same connection, where every parameter is the same, including the security settings.