C# Interview Questions
C# Interview Questions
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).
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) { }
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
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.
try {
CriticalSection.Enter(obj);
// code
}
finally
{
CriticalSection.Exit(obj);
}
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.
You must use the Missing class and pass Missing.Value (in System.Reflection) for any
values that have optional parameters.
How can you tell the application to look for assemblies at the locations
other than its own install?
Use the directive in the XML .config file for a given application.
< probing privatePath=c:\mylibs; bin\debug />
should do the trick. Or you can add additional search paths in the Properties box of the
deployed application.
Can you have two files with the same file name in GAC?
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.
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?
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.
Can you prevent your class from being inherited and becoming a base class
for some other classes?
Yes, that is 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 is the same concept as final class in Java.
Is XML case-sensitive?
Yes, so and are different elements.
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?
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.
Will finally block get executed if the exception had not occurred?
Yes.
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).
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.
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.
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
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 hasnot), 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).
Why cannot you specify the accessibility modifier for methods inside the
interface?
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 is
public by default.
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() {}
}
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) {}
}
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.
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.
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
Explain the three services model (three-tier application). Presentation (UI), business
(logic and underlying code) and data (from storage or other sources).
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).
Can I define a type that is an alias of another type (like typedef in C++)?
Not exactly. You can create an alias within a single file with the "using" directive: using
System; using Integer = System.Int32; // alias
But you can't create a true alias, one that extends beyond the file in which it is
declared. Refer to the C# spec for more info on the 'using' statement's scope.
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
What is the .NET datatype that allows the retrieval of data by a unique key?
HashTable.
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.
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.
How can you overload a method?
Different parameter data types, different number of parameters, different order of
parameters.
How can you sort the elements of the array in descending order?
By calling Sort() and then Reverse() methods.
What is a delegate?
A delegate object encapsulates a reference to a method. In C++ they were referred to as
function pointers.
How can you sort the elements of the array in descending order?
By calling Sort() and then Reverse() methods.
What’s the .NET collection class that allows an element to be accessed using
a unique key?
HashTable.
Will the finally block get executed if an exception has not occurred?
Yes.
Presentation (UI), Business (logic and underlying code) and Data (from storage or other
sources).
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.
Why can’t you specify the accessibility modifier for methods inside the interface?
They all must be public, and are therefore public by default.
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
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.
What’s a delegate?
A delegate object encapsulates a reference to a method.
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).
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. OLE-DB.NET is a .NET layer on top of the
OLE layer, so it’s not as fastest and efficient as SqlServer.NET.
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%’.
What does the Initial Catalog parameter define in the connection string?
The database name to connect to.
Answer1
DirectCast requires the run-time type of an object variable to bethe same as the
specified type.The run-time performance ofDirectCast is better than that of CType, if the
specified type and the run-time typeof the expression are the same. Ctype works fine if
there is a valid conversion defined between the expression and the type.
Answer2
The difference between the two keywords is that CType succeeds as long as there is a
valid conversion defined between the expression and the type, whereas DirectCast
requires the run-time type of an object variable to be the same as the specified type. If
the specified type and the run-time type of the expression are the same, however, the
run-time performance of DirectCast is better than that of CType.
In the preceding example, the run-time type of Q is Double. CType succeeds because
Double can be converted to Integer, but DirectCast fails because the run-time type of Q
is not already Integer
Answer2
the ctype(123.34,integer) will work fine no errors
Answer2
Manifest: Manifest describes assembly itself. Assembly Name, version number, culture,
strong name, list of all files, Type references, and referenced assemblies.
Metadata: Metadata describes contents in an assembly classes, interfaces, enums,
structs, etc., and their containing namespaces, the name of each type, its
visibility/scope, its base class, the nterfaces it implemented, its methods and their
scope, and each method’s parameters, type’s properties, and so on.
Difference between value and reference type. what are value types and reference types?
Value type - bool, byte, chat, decimal, double, enum , float, int, long, sbyte, short, strut,
uint, ulong, ushort
Value types are stored in the Stack
Reference type - class, delegate, interface, object, string
Reference types are stored in the Heap
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.
Answer2
the run time will maintain a service called as garbage collector. This service will take
care of deallocating memory corresponding to objects. it works as a thread with least
priority. when application demands for memory the runtime will take care of setting the
high priority for the garbage collector, so that it will be called for execution and memory
will be released. the programmer can make a call to garbage collector by using GC class
in system name space.
How can you clean up objects holding resources from within the code?
Call the dispose method from code for clean up of objects
How can you sort the elements of the array in descending order?
By calling Sort() and then Reverse() methods.