C Sharp Interview Questions
C Sharp Interview Questions
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).
46. 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) { }
47. 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
48. 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 {}
or
[Obsolete(\"This is a message describing why this method is obsolete\")] public int Foo() {...}
lock(obj) { // code }
translates to
try {
CriticalSection.Enter(obj);
// code
}
finally
{
CriticalSection.Exit(obj);
}
51. How do you directly call a native function exported from a DLL? - 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.
52. 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.
53. 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.
54. Why does DllImport not work for me? - All methods marked with the DllImport
attribute must be marked as public static extern.
55. 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.
56. 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)
57. Why do I get a syntax error when trying to declare a variable called
checked? - The word checked is a keyword in C#.
58. 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.
59. 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) {} }
60. 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.
61. 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() {} }
62. What is the equivalent to regsvr32 and regsvr32 /u a file in .NET
development? - Try using RegAsm.exe. Search MSDN on Assembly
Registration Tool.
63. 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.
64. 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#:
switch(x)
{
case 0: // do something
case 1: // do something as continuation of case 0
default: // do something in common with
//0, 1 and everything else
break;
}
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;
switch(x)
{
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
break;
}
}
}
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();
}
}
67. 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.
68. 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().
69. 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; j="0" j ="=">
(Access specifiers)
4.What are the access-specifiers available in c#?
Private, Protected, Public, Internal, Protected Internal.
128. 5.Explain about Protected and protected internal, ?internal? access-
specifier?
protected - Access is limited to the containing class or types derived from the
containing class.
internal - Access is limited to the current assembly.
protected internal - Access is limited to the current assembly or types derived
from the containing class.
(Constructor / Destructor)
6.Difference between type constructor and instance constructor? What is
static constructor, when it will be fired? And what is its use?
(Class constructor method is also known as type constructor or type initializer)
Instance constructor is executed when a new instance of type is created and the
class constructor is executed after the type is loaded and before any one of the
type members is accessed. (It will get executed only 1st time, when we call any
static methods/fields in the same class.) Class constructors are used for static
field initialization. Only one class constructor per type is permitted, and it cannot
use the vararg (variable argument) calling convention.
A static constructor is used to initialize a class. It is called automatically to
initialize the class before the first instance is created or any static members are
referenced.
129. 7.What is Private Constructor? and it?s use? Can you create
instance of a class which has Private Constructor?
A: When a class declares only private instance constructors, it is not possible for
classes outside the program to derive from the class or to directly create
instances of it. (Except Nested classes)
Make a constructor private if:
- You want it to be available only to the class itself. For example, you might have
a special constructor used only in the implementation of your class' Clone
method.
- You do not want instances of your component to be created. For example, you
may have a class containing nothing but Shared utility functions, and no instance
data. Creating instances ofthe class would waste memory.
130. 8.I have 3 overloaded constructors in my class. In order to avoid
making instance of the class do I need to make all constructors to private?
(yes)
131. 9.Overloaded constructor will call default constructor internally?
(no)
132. 10.What are virtual destructors?
Destructor and finalize
Generally in C++ the destructor is called when objects gets destroyed. And one
can explicitly call the destructors in C++. And also the objects are destroyed in
reverse order that they are created in. So in C++ you have control over the
destructors.
In C# you can never call them, the reason is one cannot destroy an object. So
who has the control over the destructor (in C#)? it's the .Net frameworks Garbage
Collector (GC). GC destroys the objects only when necessary. Some situations
of necessity are memory is exhausted or user explicitly calls System.GC.Collect()
method.
Points to remember:
1. Destructors are invoked automatically, and cannot be invoked explicitly.
2. Destructors cannot be overloaded. Thus, a class can have, at most, one
destructor.
3. Destructors are not inherited. Thus, a class has no destructors other than the
one, which may be declared in it.
4. Destructors cannot be used with structs. They are only used with classes.
5. An instance becomes eligible for destruction when it is no longer possible for
any code to use the instance.
6. Execution of the destructor for the instance may occur at any time after the
instance becomes eligible for destruction.
7. When an instance is destructed, the destructors in its inheritance chain are
called, in order, from most derived to least derived.
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/
cpconfinalizemethodscdestructors.asp
133. 11.What is the difference between Finalize and Dispose (Garbage
collection)
Class instances often encapsulate control over resources that are not managed
by the runtime, such as window handles (HWND), database connections, and so
on. Therefore, you should provide both an explicit and an implicit way to free
those resources. Provide implicit control by implementing the protected Finalize
Method on an object (destructor syntax in C# and the Managed Extensions for
C++). The garbage collector calls this method at some point after there are no
longer any valid references to the object.
In some cases, you might want to provide programmers using an object with the
ability to explicitly release these external resources before the garbage collector
frees the object. If an external resource is scarce or expensive, better
performance can be achieved if the programmer explicitly releases resources
when they are no longer being used. To provide explicit control, implement the
Dispose method provided by the IDisposable Interface. The consumer of the
object should call this method when it is done using the object. Dispose can be
called even if other references to the object are alive.
Note that even when you provide explicit control by way of Dispose, you should
provide implicit cleanup using the Finalize method. Finalize provides a backup to
prevent resources from permanently leaking if the programmer fails to call
Dispose.
134. 12.What is close method? How its different from Finalize & Dispose?
**
13.What is boxing & unboxing?
14.What is check/uncheck?
15.What is the use of base keyword? Tell me a practical example for base
keyword?s usage?
16.What are the different .net tools which u used in projects?
try
{
...
}
catch
{
...//exception occurred here. What'll happen?
}
finally
{
..
}
Ans : It will throw exception.
135. 17.What will do to avoid prior case?
Ans:
try
{
try
{
...
}
catch
{
...
//exception occurred here.
}
finally
{
...
}
}
catch
{
...
}
finally
{
...
}
try
{
...
}
catch
{
...
}
finally
{
..
}
136. 18.Will it go to finally block if there is no exception happened?
Ans: Yes. The finally block is useful for cleaning up any resources allocated in
the try block. Control is always passed to the finally block regardless of how the
try block exits.
137. 19.Is goto statement supported in C#? How about Java?
Gotos are supported in C#to the fullest. In Java goto is a reserved keyword that
provides absolutely no functionality.
138. 20.What?s different about switch statements in C#?
No fall-throughs allowed. Unlike the C++ switch statement, C# does not support
an explicit fall through from one case label to another. If you want, you can use
goto a switch-case, or goto default.
case 1:
cost += 25;
break;
case 2:
cost += 25;
goto case 1;
139. .What are the OOPS concepts?
1) Encapsulation: It is the mechanism that binds together code and data in
manipulates, and keeps both safe from outside interference and misuse. In short
it isolates a particular code and data from all other codes and data. A well-
defined interface controls the access to that particular code and data.
2) Inheritance: It is the process by which one object acquires the properties of
another object. This supports the hierarchical classification. Without the use of
hierarchies, each object would need to define all its characteristics explicitly.
However, by use of inheritance, an object need only define those qualities that
make it unique within its class. It can inherit its general attributes from its parent.
A new sub-class inherits all of the attributes of all of its ancestors.
3) Polymorphism: It is a feature that allows one interface to be used for general
class of actions. The specific action is determined by the exact nature of the
situation. In general polymorphism means "one interface, multiple methods", This
means that it is possible to design a generic interface to a group of related
activities. This helps reduce complexity by allowing the same interface to be used
to specify a general class of action. It is the compiler's job to select the specific
action (that is, method) as it applies to each situation.
140. 2.What is the difference between a Struct and a Class?
The struct type is suitable for representing lightweight objects such as Point,
Rectangle, and Color. Although it is possible to represent a point as a class, a
struct is more efficient in some scenarios. For example, if you declare an array of
1000 Point objects, you will allocate additional memory for referencing each
object. In this case, the struct is less expensive.
When you create a struct object using the new operator, it gets created and the
appropriate constructor is called. Unlike classes, structs can be instantiated
without using the new operator. If you do not use new, the fields will remain
unassigned and the object cannot be used until all of the fields are initialized.
It is an error to declare a default (parameterless) constructor for a struct. A
default constructor is always provided to initialize the struct members to their
default values.
It is an error to initialize an instance field in a struct.
There is no inheritance for structs as there is for classes. A struct cannot inherit
from another struct or class, and it cannot be the base of a class. Structs,
however, inherit from the base class Object. A struct can implement interfaces,
and it does that exactly as classes do.
A struct is a value type, while a class is a reference type.
141. 3.Value type & reference types difference? Example from .NET.
Integer & struct are value types or reference types in .NET?
Most programming languages provide built-in data types, such as integers and
floating-point numbers, that are copied when they are passed as arguments (that
is, they are passed by value). In the .NET Framework, these are called value
types. The runtime supports two kinds of value types:
Built-in value types
The .NET Framework defines built-in value types, such as System.Int32 and
System.Boolean, which correspond and are identical to primitive data types used
by programming languages.
User-defined value types
Your language will provide ways to define your own value types, which derive
from System.ValueType. If you want to define a type representing a value that is
small, such as a complex number (using two floating-point numbers), you might
choose to define it as a value type because you can pass the value type
efficiently by value. If the type you are defining would be more efficiently passed
by reference, you should define it as a class instead.
Variables of reference types, referred to as objects, store references to the actual
data. This following are the reference types:
class
interface
delegate
This following are the built-in reference types:
object
string
142. 4.What is Inheritance, Multiple Inheritance, Shared and Repeatable
Inheritance?
**
5.What is Method overloading?
Method overloading occurs when a class contains two methods with the same
name, but different signatures.
6.What is Method Overriding? How to override a function in C#?
Use the override modifier to modify a method, a property, an indexer, or an
event. An override method provides a new implementation of a member inherited
from a base class. The method overridden by an override declaration is known
as the overridden base method. The overridden base method must have the
same signature as the override method.
You cannot override a non-virtual or static method. The overridden base method
must be virtual, abstract, or override.
143. 7.Can we call a base class method without creating instance?
Its possible If its a static method.
Its possible by inheriting from that class also.
Its possible from derived classes using base keyword.
144. 8.You have one base class virtual function how will call that function
from derived class?
Ans:
class a
{
public virtual int m()
{
return 1;
}
}
class b:a
{
public int j()
{
return m();
}
}
145. 9.In which cases you use override and new base?
Use the new modifier to explicitly hide a member inherited from a base class. To
hide an inherited member, declare it in the derived class using the same name,
and modify it with the new modifier.
C# Language features
10.What are Sealed Classes in C#?
The sealed modifier is used to prevent derivation from a class. A compile-time
error occurs if a sealed class is specified as the base class of another class. (A
sealed class cannot also be an abstract class)
146. 11.What is Polymorphism? How does VB.NET/C# achieve
polymorphism?
**
12.class Token
{
public string Display()
{
//Implementation goes here
return "base";
}
}
class IdentifierToken:Token
{
public new string Display() //What is the use of new keyword
{
//Implementation goes here
return "derive";
}
}
static void Method(Token t)
{
Console.Write(t.Display());
}
public static void Main()
{
IdentifierToken Variable=new IdentifierToken();
Method(Variable); //Which Class Method is called here
Console.ReadLine();
}
For the above code What is the "new" keyword and Which Class Method is
called here
13.class Token
{
public virtual string Display()
{
//Implementation goes here
return "base";
}
}
class IdentifierToken:Token
{
public override string Display() //What is the use of new keyword
{
//Implementation goes here
return "derive";
}
}
static void Method(Token t)
{
Console.Write(t.Display());
}
public static void Main()
{
IdentifierToken Variable=new IdentifierToken();
Method(Variable); //Which Class Method is called here
Console.ReadLine();
}
A: Derive
147.