Monday, January 21, 2008

C# .NET Interview Q&A

1. Is it possible to inline assembly or IL in C# code?
Answer:
- No.


2. Is it possible to have different access modifiers on the get/set methods of a property?
Answer:
- 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#?
Answer:
- 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?
Answer:
- 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:
using System;
class main
{
public static void Main() {
try {
Console.WriteLine("In Try block");
return;
}
finally {
Console.WriteLine("In Finally block");
}
}
}

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).


5.
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?
Answer:

- 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) { }


6.
How does one compare strings in C#?
Answer:
- 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:
using System;
public class StringTest {
public static void Main(string[] args) {
Object nullObj = null; Object realObj = new StringTest();
int i = 10;
Console.WriteLine("Null Object is [" + nullObj + "]n" + "Real Object is [" + realObj + "]n" + "i is [" + i + "]n");
// Show string equality operators
string str1 = "foo";
string str2 = "bar";
string str3 = "bar";
Console.WriteLine("{0} == {1} ? {2}", str1, str2, str1 == str2 );
Console.WriteLine("{0} == {1} ? {2}", str2, str3, str2 == str3 ); }
}

Output:

Null Object is []
Real Object is [StringTest]
i is [10]
foo == bar ? False
bar == bar ? True

7.
How do you specify a custom attribute for the entire assembly (rather than for a class)?
Answer:
- 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:
using System;
[assembly : MyAttributeClass] class X {}

Note that in an IDE-created project, by convention, these attributes are placed in AssemblyInfo.cs.


8.
How do you mark a method obsolete?
Answer:
[Obsolete] public int Foo() {...}

or

[Obsolete("This is a message describing why this method is obsolete")] public int Foo() {...}

Note: The O in Obsolete is always capitalized.


9. How do you implement thread synchronization (Object.Wait, Notify,and CriticalSection) in C#?
Answer:

- You want the lock statement, which is the same as Monitor Enter/Exit:
lock(obj) { // code }

translates to

try {
CriticalSection.Enter(obj);
// code
}
finally
{ CriticalSection.Exit(obj); }

10. How do you directly call a native function exported from a DLL?
Answer:
- Here’s a quick example of the DllImport attribute in action:
using System.Runtime.InteropServices;
class C
{
[DllImport("user32.dll")]
public static extern int MessageBoxA(int h, string m, string c, int type);
public static int Main()
{ return MessageBoxA(0, "Hello World!", "Caption", 0); }
}

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.


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

12. The C# keyword ‘int’ maps to which .NET type?

  • System.Int16
  • System.Int32
  • System.Int64
  • System.Int128

13. Which of these string definitions will prevent escaping on backslashes in C#?

  • string s = #”n Test string”;
  • string s = “’n Test string”;
  • string s = @”n Test string”;
  • string s = “n Test string”;

14. Which of these statements correctly declares a two-dimensional array in C#?

  • int[,] myArray;
  • int[][] myArray;
  • int[2] myArray;
  • System.Array[2] myArray;

15. If a method is marked as protected internal who can access it?

  • Classes that are both in the same assembly and derived from the declaring class.
  • Only methods that are in the same class as the method in question.
  • Internal methods can be only be called using reflection.
  • Classes within the same assembly, and classes derived from the declaring class.


16. What is boxing?

a) Encapsulating an object in a value type.
b) Encapsulating a copy of an object in a value type.
c) Encapsulating a value type in an object.
d) Encapsulating a copy of a value type in an object.


17. What compiler switch creates an xml file from the xml comments in the files in an assembly?

  • /text
  • /doc
  • /xml
  • /help

18. What is a satellite Assembly?

  • A peripheral assembly designed to monitor permissions requests from an application.
  • Any DLL file used by an EXE file.
  • An assembly containing localized resources for another assembly.
  • An assembly designed to alter the appearance or ‘skin’ of an application.

19. What is a delegate?

  • A strongly typed function pointer.
  • A light weight thread or process that can call a single method.
  • A reference to an object in a different process.
  • An inter-process message channel.

20. How does assembly versioning in .NET prevent DLL Hell?

  • The runtime checks to see that only one version of an assembly is on the machine at any one time.
  • .NET allows assemblies to specify the name AND the version of any assemblies they need to run.
  • The compiler offers compile time checking for backward compatibility.
  • It doesn’t.

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

  • TestAttribute
  • TestClassAttribute
  • TestFixtureAttribute
  • NUnitTestClassAttribute

22. Which of the following operations can you NOT perform on an ADO.NET DataSet?

  • A DataSet can be synchronised with the database.
  • A DataSet can be synchronised with a RecordSet.
  • A DataSet can be converted to XML.
  • You can infer the schema from a DataSet.

23. In Object Oriented Programming, how would you describe encapsulation?

  • The conversion of one type of object to another.
  • The runtime resolution of method calls.
  • The exposition of data.
  • The separation of interface and implementation.

24. What’s the implicit name of the parameter that gets passed into the class’ set method?
Answer:
Value, and it’s datatype depends on whatever variable we’re changing.


25.
How do you inherit from a class in C#?
Answer:
Place a colon and then the name of the base class.


26.
Does C# support multiple inheritance?
Answer:
No, use interfaces instead.


27.
When you inherit a protected class-level variable, who is it available to?
Answer:
Access is limited to the containing class or types derived from the containing class.


28.
Are private class-level variables inherited?
Answer:
Yes, but they are not accessible, so looking at it you can honestly say that they are not inherited. But they are.


29.
Describe the accessibility modifier protected internal.
Answer:
It’s available to derived classes and classes within the same Assembly (and naturally from the base class it’s declared in).


30.
C# provides a default constructor for me. I write a constructor that takes a string as a parameter, but want to keep the no parameter one. How many constructors should I write?
Answer:
Two. Once you write at least one constructor, C# cancels the freebie constructor, and now you have to write one yourself, even if there’s no implementation in it.


31.
What’s the top .NET class that everything is derived from?
Answer:
System.Object.


32.
How’s method overriding different from overloading?
Answer:
When overriding, you change the method behavior for a derived class. Overloading simply involves having a method with the same name within the class.


33.
What does the keyword virtual mean in the method definition?
Answer:
The method can be over-ridden.


34.
Can you declare the override method static while the original method is non-static?
Answer:
No, you can’t, the signature of the virtual method must remain the same, only the keyword virtual is changed to keyword override.


35.
Can you override private virtual methods?
Answer:
No, moreover, you cannot access private methods in inherited classes, have to be protected in the base class to allow any sort of access.


36.
Can you prevent your class from being inherited and becoming a base class for some other classes?
Answer:
Yes, that’s what keyword sealed in the class definition is for. The developer trying to derive from your class will get a message: cannot inherit from Sealed class WhateverBaseClassName. It’s the same concept as final class in Java.


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


38.
What’s an abstract class?
Answer:
A class that cannot be instantiated. A concept in C++ known as pure virtual method. A class that must be inherited and have the methods over-ridden. Essentially, it’s a blueprint for a class without any implementation.


39.
When do you absolutely have to declare a class as abstract (as opposed to free-willed educated choice or decision based on UML diagram)?
Answer:
When at least one of the methods in the class is abstract. When the class itself is inherited from an abstract class, but not all base abstract methods have been over-ridden.


40.
What’s an interface class?
Answer:
It’s an abstract class with public abstract methods all of which must be implemented in the inherited classes.


41.
Why can’t you specify the accessibility modifier for methods inside the interface?
Answer:
They all must be public. Therefore, to prevent you from getting the false impression that you have any freedom of choice, you are not allowed to specify any accessibility, it’s public by default.


42.
Can you inherit multiple interfaces?
Answer:
Yes, why not.


43.
And if they have conflicting method names?
Answer:
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.


44.
What’s the difference between an interface and abstract class?
Answer:
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.


45.
How can you overload a method?
Answer:
Different parameter data types, different number of parameters, different order of parameters.


46.
If a base class has a bunch of overloaded constructors, and an inherited class has another bunch of overloaded constructors, can you enforce a call from an inherited constructor to an arbitrary base constructor?
Answer:
Yes, just place a colon, and then keyword base (parameter list to invoke the appropriate constructor) in the overloaded constructor definition inside the inherited class.


47.
What’s the difference between System.String and System.StringBuilder classes?
Answer:
System.String is immutable, System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed.


48.
Is it namespace class or class namespace?
Answer:
The .NET class library is organized into namespaces. Each namespace contains a functionally related group of classes so natural namespace comes first.


49. How big is the datatype int in .NET?
Answer:
32 bits.


50.
How big is the char?
Answer:
16 bits (Unicode).


51.
How do you initiate a string without escaping each backslash?
Answer:
Put an @ sign in front of the double-quoted string.


52.
What are valid signatures for the Main function?
Answer:
public static void Main()
public static int Main()
public static void Main( string[] args )
public static int Main(string[] args )


53.
Does Main() always have to be public?
Answer:
No.


54.
How do you initialize a two-dimensional array that you don’t know the dimensions of?
Answer:
int [, ] myArray; //declaration
myArray= new int [5, 8]; //actual initialization


55.
What’s the access level of the visibility type internal?
Answer:
Current assembly.


56.
What’s the difference between struct and class in C#?
Answer:
- Structs cannot be inherited.
- Structs are passed by value, not by reference.
- Struct is stored on the stack, not the heap.


57.
Explain encapsulation.
Answer:
The implementation is hidden, the interface is exposed.


58.
What data type should you use if you want an 8-bit value that’s signed?
Answer:
sbyte.


59.
Speaking of Boolean data types, what’s different between C# and C/C++?
Answer:
There’s no conversion between 0 and false, as well as any other number and true, like in C/C++.


60.
Where are the value-type variables allocated in the computer RAM?
Answer:
Stack.


61.
Where do the reference-type variables go in the RAM?
Answer:
The references go on the stack, while the objects themselves go on the heap. However, in reality things are more elaborate.


62.
What is the difference between the value-type variables and reference-type variables in terms of garbage collection?
Answer:
The value-type variables are not garbage-collected, they just fall off the stack when they fall out of scope, the reference-type objects are picked up by GC when their references go null.


63.
How do you convert a string into an integer in .NET?
Answer:
Int32.Parse(string), Convert.ToInt32()


64.
How do you box a primitive data type variable?
Answer:
Initialize an object with its value, pass an object, cast it to an object


65.
Why do you need to box a primitive variable?
Answer:
To pass it by reference or apply a method that an object supports, but primitive doesn’t.


66.
What’s the difference between Java and .NET garbage collectors?
Answer:
Sun left the implementation of a specific garbage collector up to the JRE developer, so their performance varies widely, depending on whose JRE you’re using. Microsoft standardized on their garbage collection.


67.
How do you enforce garbage collection in .NET?
Answer:
System.GC.Collect();


68.
Can you declare a C++ type destructor in C# like ~MyClass()?
Answer:
Yes, but what’s the point, since it will call Finalize(), and Finalize() has no guarantees when the memory will be cleaned up, plus, it introduces additional load on the garbage collector. The only time the finalizer should be implemented, is when you’re dealing with unmanaged code.


69.
What’s different about namespace declaration when comparing that to package declaration in Java?
Answer:
No semicolon. Package declarations also have to be the first thing within the file, can’t be nested, and affect all classes within the file.


70.
What’s the difference between const and readonly?
Answer:
You can initialize readonly variables to some runtime values. Let’s say your program uses current date and time as one of the values that won’t change. This way you declare:
public readonly string DateT = new DateTime().ToString().

71.
Can you create enumerated data types in C#?
Answer:
Yes.


72.
What’s different about switch statements in C# as compared to C++?
Answer:
No fall-throughs allowed.


73.
What happens when you encounter a continue statement inside the for loop?
Answer:
The code for the rest of the loop is ignored, the control is transferred back to the beginning of the loop.


74.
Is goto statement supported in C#? How about Java?
Answer:
Gotos are supported in C#to the fullest. In Java goto is a reserved keyword that provides absolutely no functionality.


75.
Describe the compilation process for .NET code?
Answer:
Source code is compiled and run in the .NET Framework using a two-stage process. First, source code is compiled to Microsoft intermediate language (MSIL) code using a .NET Framework compatible compiler, such as that for Visual Basic .NET or Visual C#. Second, MSIL code is compiled to native code.


76.
Name any 2 of the 4 .NET authentification methods.
Answer:
ASP.NET, in conjunction with Microsoft Internet Information Services (IIS), can authenticate user credentials such as names and passwords using any of the following authentication methods:
  • Windows: Basic, digest, or Integrated Windows Authentication (NTLM or Kerberos).
  • Microsoft Passport authentication
  • Forms authentication
  • Client Certificate authentication

77. What is main difference between Global.asax and Web.Config?
Answer:
ASP.NET uses the global.asax to establish any global objects that your Web application uses. The .asax extension denotes an application file rather than .aspx for a page file. Each ASP.NET application can contain at most one global.asax file. The file is compiled on the first page hit to your Web application. ASP.NET is also configured so that any attempts to browse to the global.asax page directly are rejected. However, you can specify application-wide settings in the web.config file. The web.config is an XML-formatted text file that resides in the Web site’s root directory. Through Web.config you can specify settings like custom 404 error pages, authentication and authorization settings for the Web site, compilation options for the ASP.NET Web pages, if tracing should be enabled, etc.