Interview Questions : C#
1. What does the modifier protected internal in C# mean?
The Protected Internal can be accessed by Members of the Assembly or the inheriting class, and of course, within the class itself.
In VB.NET, the equivalent of protected internal is protected friend.
2. What's C# ?
C# (pronounced C-sharp) is a new object oriented language from Microsoft and is derived from C and C++. It also borrows a lot of concepts from Java too including garbage collection.
3. Is it possible to inline assembly or IL in C# code?
No
4. 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.
5. Is it possible to have a static indexer in C#? allowed in C#.
No. Static indexers are not
6. 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:
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).
7. 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) { }
8. 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:
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
9. 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:
using System;
[assembly : MyAttributeClass] class X {}
Note that in an IDE-created project, by convention, these attributes are placed in AssemblyInfo.cs.
How do you mark a method obsolete?
[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.
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:
lock(obj) { // code }
translates to
try {
CriticalSection.Enter(obj);
// code
}
finally
{
CriticalSection.Exit(obj);
}
10. What is the C# equivalent of C++ catch (…), which was a catch-all statement for any possible exception? Does C# support try-catch-finally blocks?
Yes. Try-catch-finally blocks are supported by the C# compiler. Here's an example of a try-catch-finally block: using System;
public class TryTest
{
static void Main()
{
try
{
Console.WriteLine("In Try block");
throw new ArgumentException();
}
catch(ArgumentException n1)
{
Console.WriteLine("Catch Block");
}
finally
{
Console.WriteLine("Finally Block");
}
}
}
Output: In Try Block
Catch Block
Finally Block
11. 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, as shown in the following
example: 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).
12. Is there regular expression (regex) support available to C# developers?
Yes. The .NET class libraries provide support for regular expressions. Look at the documentation for the System.Text.RegularExpressions namespace.
13. Does C# support properties of array types?
Yes. Here's a simple example: using System;
class Class1
{
private string[] MyField;
public string[] MyProperty
{
get { return MyField; }
set { MyField = value; }
}
}
class MainClass
{
public static int Main(string[] args)
{
Class1 c = new Class1();
string[] arr = new string[] {"apple", "banana"};
c.MyProperty = arr;
Console.WriteLine(c.MyProperty[0]); // "apple"
return 0;
}
}
14. How is method overriding different from overloading?
When overriding, you change the method behavior for a derived class. Overloading simply involves having a method with the same name within the class.
15. When do you absolutely have to declare a class as abstract (as opposed to free-willed educated choice or decision based on UML diagram)?
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.
16. Why would you use untrusted verification?
Web Services might use it, as well as non-Windows applications.
17. What is the implicit name of the parameter that gets passed into the class set method?
Value, and its datatype depends on whatever variable we are changing.
18. How do I register my code for use by classic COM clients?
Use the regasm.exe utility to generate a type library (if needed) and the necessary entries in the Windows Registry to make a class available to classic COM clients. Once a class is registered in the Windows Registry with regasm.exe, a COM client can use the class as though it were a COM class.
19. How do I do implement a trace and assert?
Use a conditional attribute on the method, as shown below:
class Debug
{
[conditional("TRACE")]
public void Trace(string s)
{
Console.WriteLine(s);
}
}
class MyClass
{
public static void Main()
{
Debug.Trace("hello");
}
}
In this example, the call to Debug.Trace() is made only if the preprocessor symbol TRACE is defined at the call site. You can define preprocessor symbols on the command line by using the /D switch. The restriction on conditional methods is that they must have void return type.
20. 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() {}
}
21. What does the keyword virtual mean in the method definition?
The method can be over-ridden.
22. 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 w/ an empty try.
We get rid of try-finally w/ an empty try (convert to normal code...).
We get rid of try-finally w/ an empty finally (convert to normal code...).
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.
23. How can I create a process that is running a supplied native executable (e.g., cmd.exe)?
The following code should run the executable and wait for it to exit before
continuing: using System;
using System.Diagnostics;
public class ProcessTest {
public static void Main(string[] args) {
Process p = Process.Start(args[0]);
p.WaitForExit();
Console.WriteLine(args[0] + " exited.");
}
}
Remember to add a reference to System.Diagnostics.dll when you compile.
24. What is 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.
How do I declare inout arguments in C#?
The equivalent of inout in C# is ref. , as shown in the following
example: public void MyMethod (ref String str1, out String str2)
{
...
}
When calling the method, it would be called like this: String s1;
String s2;
s1 = "Hello";
MyMethod(ref s1, out s2);
Console.WriteLine(s1);
Console.WriteLine(s2);
Notice that you need to specify ref when declaring the function and calling it.
25. 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: using System;
class BreakExample
{
public static void Main(String[] args)
{
for(int i=0; i<3; i++)
{
Console.WriteLine("Pass {0}: ", i);
for( int j=0 ; j<100 ; j++ )
{
if ( j == 10) goto done;
Console.WriteLine("{0} ", j);
}
Console.WriteLine("This will not print");
}
done:
Console.WriteLine("Loops complete.");
}
}
26. What is the difference between const and static read-only?
The difference is that static read-only can be modified by the containing class, but const can never be modified and must be initialized to a compile time constant. To expand on the static read-only case a bit, the containing class can only modify it: -- in the variable declaration (through a variable initializer).
-- in the static constructor (instance constructors if it's not static).
27. What is the difference between System.String and System.StringBuilder classes?
System.String is immutable; System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed.
28. What is the top .NET class that everything is derived from?
System.Object.
29. Can you allow class to be inherited, but prevent the method from being over-ridden?
Yes, just leave the class public and make the method sealed
30. 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.
31. 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.
32. Can you inherit multiple interfaces?
Yes. .NET does support multiple interfaces.
33. 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.
34. Is there any sample C# code for simple threading?
Some sample code follows: using System;
using System.Threading;
class ThreadTest
{
public void runme()
{
Console.WriteLine("Runme Called");
}
public static void Main(String[] args)
{
ThreadTest b = new ThreadTest();
Thread t = new Thread(new ThreadStart(b.runme));
t.Start();
}
}
35. What is the difference between // comments, /* */ comments and /// comments?
Single-line, multi-line and XML documentation comments.
36. How do you inherit from a class in C#?
Place a colon and then the name of the base class. Notice that it is double colon in C++.
37. Is it possible to have a static indexer in C#?
No. Static indexers are not allowed in C#.
38. Does C# support #define for defining global constants?
No. If you want to get something that works like the following C code:
#define A 1
use the following C# code: class MyConstants
{
public const int A = 1;
}
Then you use MyConstants.A where you would otherwise use the A macro.
Using MyConstants.A has the same generated code as using the literal 1.
39. Does C# support templates?
No. However, there are plans for C# to support a type of template known as a generic. These generic types have similar syntax but are instantiated at run time as opposed to compile time. You can read more about them here.
40. Does C# support parameterized properties?
No. C# does, however, support the concept of an indexer from language spec. An indexer is a member that enables an object to be indexed in the same way as an array. Whereas properties enable field-like access, indexers enable array-like access. As an example, consider the Stack class presented earlier. The designer of this class may want to expose array-like access so that it is possible to inspect or alter the items on the stack without performing unnecessary Push and Pop operations. That is, Stack is implemented as a linked list, but it also provides the convenience of array access.
Indexer declarations are similar to property declarations, with the main differences being that indexers are nameless (the name used in the declaration is this, since this is being indexed) and that indexers include indexing parameters. The indexing parameters are provided between square brackets.
41. Does C# support C type macros?
No. C# does not have macros. Keep in mind that what some of the predefined C macros (for example, __LINE__ and __FILE__) give you can also be found in .NET classes like System.Diagnostics (for example, StackTrace and StackFrame), but they'll only work on debug builds.
42. Can you store multiple data types in System.Array?
No.
43. Is it possible to inline assembly or IL in C# code?
No.
44. Can you declare the override method static while the original method is non-static?
No, you cannot, the signature of the virtual method must remain the same, only the keyword virtual is changed to keyword override
45. Does C# support multiple inheritance?
No, use interfaces instead.
46. 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.
47. Can you override private virtual methods?
No, moreover, you cannot access private methods in inherited classes, have to be protected in the base class to allow any sort of access.
48. 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,
49. What is the data provider name to connect to Access database?
Microsoft.Access.
50. 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.
51. Describe the accessibility modifier protected internal?
It is available to derived classes and classes within the same Assembly (and naturally from the base class it is declared in).
52. What is an interface class?
It is an abstract class with public abstract methods all of which must be implemented in the inherited classes.
53. What is a multicast delegate?
It is a delegate that points to and eventually fires off several methods.
54. 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: 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
55. How do I convert a string to an int in C#?
Here's an example: using System;
class StringToInt
{
public static void Main()
{
String s = "105";
int x = Convert.ToInt32(s);
Console.WriteLine(x);
}
}
56. 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.
What is 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.
57. How can you overload a method?
Different parameter data types, different number of parameters, different order of parameters.
58. How do destructors and garbage collection work in C#?
C# has finalizers (similar to destructors except that the runtime doesn't guarantee they'll be called), and they are specified as follows:
class C
{
~C()
{
// your code
}
public static void Main() {}
}
Currently, they override object.Finalize(), which is called during the GC process.
How can I access the registry from C# code?
By using the Registry and RegistryKey classes in Microsoft.Win32, you can easily access the registry. The following is a sample that reads a key and displays its value:
using System;using Microsoft.Win32;
class regTest
{
public static void Main(String[] args)
{
RegistryKey regKey;
Object value;
regKey = Registry.LocalMachine;
regKey =
regKey.OpenSubKey("HARDWAREDESCRIPTIONSystemCentralProcessor ");
value = regKey.GetValue("VendorIdentifier");
Console.WriteLine("The central processor of this machine is: {0}.", value);
}
}
59. How can you sort the elements of the array in descending order?
By calling Sort() and then Reverse() methods.
How do you debug an ASP.NET Web application?
Attach the aspnet_wp.exe process to the DbgClr debugger.
How do you mark a method obsolete?
Assuming you've done a "using System;": [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 capitalized.
How is the DLL Hell problem solved in .NET?
Assembly versioning allows the application to specify not only the library it needs to run (which was available under Win32), but also the version of the assembly
60. What are the ways to deploy an assembly?
An MSI installer, a CAB archive, and XCOPY command.
61. Why does DllImport not work for me?
All methods marked with the DllImport attribute must be marked as public static extern.
62. What is a delegate?
A delegate object encapsulates a reference to a method. In C++ they were referred to as function pointers.
63. What is the difference between an interface and abstract class?
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.
64. What is an abstract class?
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 is a blueprint for a class without any implementation.
_break
65. Does C# support multiple-inheritance?
No.
66. Who is a protected class-level variable available to?
It is available to any sub-class (a class inheriting this class).
67. Can you store multiple data types in System.Array?
No.
68. What’s the top .NET class that everything is derived from?
System.Object.
69. What does the term immutable mean?
The data value may not be changed. Note: The variable value may be changed, but the original immutable data value was discarded and a new data value was created in memory.
70. What’s the difference between System.String and System.Text.StringBuilder classes?
System.String is immutable. System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed.
71. What class is underneath the SortedList class?
A sorted HashTable.
72. Will the finally block get executed if an exception has not occurred?
Yes.
73. What’s the C# syntax to catch 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 {}.
74. Can multiple catch blocks be executed for a single try statement?
No. Once the proper catch block processed, control is transferred to the finally block (if there are any).
75. Explain the three services model commonly know as a three-tier application.
Presentation (UI), Business (logic and underlying code) and Data (from storage or other sources).
76. What is the syntax to inherit from a class in C#?
Place a colon and then the name of the base class.
Example: class MyNewClass : MyBaseClass
Can you prevent your class from being inherited by another class?
Yes. The keyword “sealed” will prevent the class from being inherited.
Can you allow a class to be inherited, but prevent the method from being over-ridden?
Yes. Just leave the class public and make the method sealed.
77. What is an interface class?
Interfaces, like classes, define a set of properties, methods, and events. But unlike classes, interfaces do not provide implementation. They are implemented by classes, and defined as separate entities from classes.
78. Why can’t you specify the accessibility modifier for methods inside the interface?
They all must be public, and are therefore public by default.
79. What happens if you inherit multiple interfaces and they have conflicting method names?
It’s up to you to implement the method inside your own class, so implementation is left entirely up to you. This might cause a problem on a higher-level scale if similarly named methods from different interfaces expect different data, but as far as compiler cares you’re okay.
To Do: Investigate
80. What’s the difference between an interface and abstract class?
In an interface class, all methods are abstract - there is no implementation. In an abstract class some methods can be concrete. In an interface class, no accessibility modifiers are allowed. An abstract class may have accessibility modifiers.
81. What is the difference between a Struct and a Class?
Struts are value-type variables and are thus saved on the stack, additional overhead but faster retrieval. Another difference is that struts cannot inherit.
82. What’s the implicit name of the parameter that gets passed into the set method/property of a class?
Value. The data type of the value parameter is defined by whatever data type the property is declared as.
83. What does the keyword “virtual” declare for a method or property?
The method or property can be overridden.
84. How is method overriding different from method overloading?
When overriding a method, you change the behavior of the method for the derived class. Overloading a method simply involves having another method with the same name within the class.
85. Can you declare an override method to be static if the original method is not static?
No. The signature of the virtual method must remain the same. (Note: Only the keyword virtual is changed to keyword override)
86. What are the different ways a method can be overloaded?
Different parameter data types, different number of parameters, different order of parameters.
87. If a base class has a number of overloaded constructors, and an inheriting class has a number of overloaded constructors; can you enforce a call from an inherited constructor to a specific base constructor?
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.
88. What’s a delegate?
A delegate object encapsulates a reference to a method.
89. What’s a multicast delegate?
A delegate that has multiple handlers assigned to it. Each assigned handler (method) is called.
90. Why are there five tracing levels in System.Diagnostics.TraceSwitcher?
The tracing dumps can be quite verbose. For applications that are constantly running you run the risk of overloading the machine and the hard drive. Five levels range from None to Verbose, allowing you to fine-tune the tracing activities.
91. Where is the output of TextWriterTraceListener redirected?
To the Console or a text file depending on the parameter passed to the constructor.
How do you debug an ASP.NET Web application?
Attach the aspnet_wp.exe process to the DbgClr debugger.
92. What are three test cases you should go through in unit testing?
1. Positive test cases (correct data, correct output).
2. Negative test cases (broken or missing data, proper handling).
3. Exception test cases (exceptions are thrown and caught properly).
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.
93. Explain constructor.
Constructor is a method in the class which has the same name as the class (in VB.Net its New()). It initializes the member attributes whenever an instance of the class is created.
94. What is Delegation?
A delegate acts like a strongly type function pointer. Delegates can invoke the methods that they reference without making explicit calls to those methods.
Delegate is an entity that is entrusted with the task of representation, assign or passing on information. In code sense, it means a Delegate is entrusted with a Method to report information back to it when a certain task (which the Method expects) is accomplished outside the Method's class.