C# interview questions and answers
- What’s the advantage of using
System.Text.StringBuilder over System.String? 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.
- Can you store multiple data
types in System.Array? No.
- What’s 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 can you sort the elements
of the array in descending order? By
calling Sort() and then Reverse() methods.
- What’s the .NET datatype that
allows the retrieval of data by a unique key? HashTable.
- What’s class SortedList underneath?
A sorted HashTable.
- Will finally block get
executed if the exception had not occurred? Yes.
- What’s the C# equivalent of
C++ catch (…), which was a catch-all statement for 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 {}.
- 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.
- Why is it a bad idea to throw
your own exceptions? 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.
- What’s a delegate? A delegate object encapsulates a reference to a method.
In C++ they were referred to as function pointers.
- What’s a multicast delegate? It’s a delegate that points to and eventually fires off
several methods.
- How’s 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.
- What are the ways to deploy
an assembly? An MSI installer, a CAB
archive, and XCOPY command.
- What’s a satellite assembly? 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.
- What namespaces are necessary
to create a localized application? System.Globalization,
System.Resources.
- What’s the difference between
// comments, /* */ comments and /// comments? Single-line, multi-line and XML documentation comments.
- How do you generate
documentation from the C# file commented properly with a command-line
compiler? Compile it with a /doc switch.
- What’s the difference between
<c> and <code> XML documentation tag? Single line code example and multiple-line code
example.
- Is XML case-sensitive? Yes, so <Student> and <student> are
different elements.
- What debugging tools come
with the .NET SDK? 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.
- What does the This window
show in the debugger? It
points to the object that’s pointed to by this reference. Object’s instance
data is shown.
- What does assert() do? 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.
- What’s 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.
- Why are there five tracing
levels in System.Diagnostics.TraceSwitcher? 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.
- 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.
- 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 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.
- Explain the three services
model (three-tier application). Presentation
(UI), business (logic and underlying code) and data (from storage or other
sources).
- What are advantages and
disadvantages of Microsoft-provided data provider classes in ADO.NET? 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.
- What’s the role of the
DataReader class in ADO.NET connections? It
returns a read-only dataset from the data source when the command is
executed.
- 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%’.
- Explain ACID rule of thumb
for transactions. 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).
- What connections does
Microsoft SQL Server support? Windows
Authentication (via Active Directory) and SQL Server authentication (via
Microsoft SQL Server username and passwords).
- Which one is trusted and
which one is untrusted? 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.
- Why would you use untrusted
verificaion? Web Services might use it, as
well as non-Windows applications.
- What does the parameter
Initial Catalog define inside Connection String? The database name to connect to.
- What’s the data provider name
to connect to Access database? Microsoft.Access.
- What does Dispose method do
with the connection object? Deletes
it from the memory.
- 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, including the security settings.
C# , ASP.NET, VB.NET, ADO.NET, SQL
Server, Ripal Soni
.Net 2.0 Interview Terms /
Interview Questions Crystal Reports – For Visual Studio 2005
Walkthroughs – Contents
June 6, 2007
1. What
standard types does C# use? C#
supports a very similar range of basic types to C++, including int, long,
float, double, char, string, arrays, structs and classes. In C# Types The names
may be familiar, but many of the details are different. For example, a long is
64 bits in C#, whereas in C++ the size of a long depends on the platform
(typically 32 bits on a 32-bit platform, 64 bits on a 64-bit platform). Also
classes and structs are almost the same in C++ – this is not true for C#.
Finally, chars and strings in .NET are 16-bit (Unicode/UTF-16), not 8-bit like
C++.
2.What is
the syntax to inherit from a class in C#?
Place a colon and then the name of
the base class.
Public class derivedclass:baseclass
3.How can
I make sure my C# classes will interoperate with other .Net languages?
Make sure your C# code conforms to
the Common Language Subset (CLS). To help with this, add the [assembly:
CLSCompliant (true)] global attribute to your C# source files. The compiler
will emit an error if you use a C# feature which is not CLS-compliant.
4.Does C#
support variable argument on method?The
params keyword can be applied on a method parameter that is an array. When the
method is invoked, the elements of the array can be supplied as a comma
separated list.So, if the method parameter is an object array,
void paramsExample(object arg1, object arg2, params object[]
argsRest)
{
foreach (object arg in argsRest)
{
/* .... */
}
}
then the method can be invoked with
any number of arguments of any type.paramsExample(1, 0.0f, “a string”, 0.0m,
new UserDefinedType());
5.What’s
the difference between const and readonly?
Readonly
fields are delayed initalized constants. However they have one more thing
different is that; When we declare a field as const it is treated as a static
field. where as the Readonly fields are treated as normal class variables.const
keyword used ,when u want’s value constant at compile time but in case of
readonly ,value constant at run timeForm the use point of view if we want a
field that can have differnet values between differnet objects of same class,
however the value of the field should not change for the life span of object;
We should choose the Read Only fields rather than constants.Since the constants
have the same value accross all the objects of the same class; they are treated
as static.
6.What is
the difference about Switch statement 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;
7. What is
the difference between a static and an instance constructor?
An
instance constructor implements code to initialize the instance of the class. A
static constructor implements code to initialize the class itself when it is
first loaded.
8. Assume
that a class, Class1, has both instance and static constructors. Given the code
below, how many times will the static and instance constructors fire?
Class1 c1 = new Class1();
Class1 c2 = new Class1();
Class1 c3 = new Class1();
By
definition, a static constructor is fired only once when the class is loaded.
An instance constructor on the other hand is fired each time the class is
instantiated. So, in the code given above, the static constructor will fire
once and the instance constructor will fire three times.
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.
10.You
have one base class virtual function how will you call the function from
derived class?
class a
{
public virtual int m()
{
return 1;
}
}
class b:a
{
public int j()
{
return m();
}
}
11. Can we
call a base class method without creating instance?
It is
possible if it’s a static method.
It is
possible by inheriting from that class also.It is possible from derived classes
using base keyword.
12. What
is Method Overriding? How to override a function in C#?
Method
overriding is a feature that allows you to invoke functions (that have the same
signatures) that belong to different classes in the same hierarchy of
inheritance using the base class reference. C# makes use of two keywords:
virtual and overrides to accomplish Method overriding. Let’s understand this
through small examples.
class BC
{
public void Display()
{
System.Console.WriteLine("BC::Display");
}
}
class DC : BC
{
new public void Display()
{
System.Console.WriteLine("DC::Display");
}
}
class Demo
{
public static void
Main()
{
BC b;
b = new BC();
b.Display();
}
}
Output :
BC::Display
13. What
is an Abstract Class?
A class
that cannot be instantiated. An abstract class is a class that must be
inherited and have the methods overridden. An abstract class is essentially a
blueprint for a class without any implementation.
14.When do
you absolutely have to declare a class as abstract?
1. When
the class itself is inherited from an abstract class, but not all base abstract
methods have been overridden.
2. When at
least one of the methods in the class is abstract.
15. 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.
16.Can you
inherit multiple interfaces?
Yes. .NET
does support multiple interfaces.
17.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.
18. 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.
19. Why
can’t you specify the accessibility modifier for methods inside the interface?
They all
must be public, and are therefore public by default.
20.
Describe the accessibility modifier “protected internal”.
It is
available to classes that are within the same assembly and derived from the
specified base class.
21. 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 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.
22. What
are the different ways a method can be overloaded?
Different
parameter data types, different number of parameters, different order of
parameters.
23. 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()
{…}
24. What
is a sealed class?
It is a
class, which cannot be subclassed. It is a good practice to mark your classes
as sealed, if you do not intend them to be subclassed.
25. How do
you prevent a class from being inherited?
Mark it as
sealed.
26. Can
you inherit from multiple base classes in C#?
No. C#
does not support multiple inheritance, so you cannot inherit from more than one
base class. You can however, implement multiple interfaces.
27. What
is an indexer in C#?
The
indexers are usually known as smart arrays in C# community. Defining a C#
indexer is much like defining properties. We can say that an indexer is a
member that enables an object to be indexed in the same way as an array.
class MyClass
{
private string []data = new
string[5];
public string this [int index]
{
get
{
return data[index];
}
set
{
data[index] = value;
}
}
}
Where the
modifier can be private, public, protected or internal. The return type can be
any valid C# types. The ‘this’ is a special keyword in C# to indicate the
object of the current class. The formal-argument-list specifies the parameters
of the indexer.
28. What
is the use of fixed statement?
The fixed
statement sets a pointer to a managed variable and “pins” that variable during
the execution of statement.
Without
fixed, pointers to managed variables would be of little use since garbage
collection could relocate the variables unpredictably. (In fact, the C#
compiler will not allow you to set a pointer to a managed variable except in a
fixed statement.)
Class A
{
public int i;
}
A objA = new A; // A is a .net
managed type
fixed(int *pt = &objA.i) //
use fixed while using pointers with managed
// variables
{
*pt=45; // in this block use the
pointer the way u want
}
29. What
is the order of destructors called in a polymorphism hierarchy?
Destructors
are called in reverse order of constructors. First destructor of most derived
class is called followed by its parent’s destructor and so on till the topmost
class in the hierarchy.
You don’t
have control over when the first destructor will be called, since it is
determined by the garbage collector. Sometime after the object goes out of
scope GC calls the destructor, then its parent’s destructor and so on.
When a
program terminates definitely all object’s destructors are called.
30. What
is a virtual method?
Ans.In C#,
virtual keyword can be used to mark a property or method to make it
overrideable. Such methods/properties are called virtual methods/properties.By
default, methods and properties in C# are non-virtual.
31. Is it
possible to Override Private Virtual methods?
No, First
of all you cannot declare a method as ‘private virtual’.
32. Can I
call a virtual method from a constructor/destructor?
Yes, but
it’s generally not a good idea. The mechanics of object construction in .NET
are quite different from C++, and this affects virtual method calls in
constructors.C++ constructs objects from base to derived, so when the base
constructor is executing the object is effectively a base object, and virtual
method calls are routed to the base class implementation. By contrast, in .NET
the derived constructor is executed first, which means the object is always a
derived object and virtual method calls are always routed to the derived
implementation. (Note that the C# compiler inserts a call to the base class
constructor at the start of the derived constructor, thus preserving standard
OO semantics by creating the illusion that the base constructor is executed
first.)The same issue arises when calling virtual methods from C# destructors.
A virtual method call in a base destructor will be routed to the derived
implementation.
33. How do
I declare a pure virtual function in C#?
Use the
abstract modifier on the method. The class must also be marked as abstract
(naturally). Note that abstract methods cannot have an implementation (unlike
pure virtual C++ methods).
34. Are
all methods virtual in C#?
No. Like
C++, methods are non-virtual by default, but can be marked as virtual.
35. What
is the difference between shadow and override?
When you
define a class that inherits from a base class, you sometimes want to redefine
one or more of the base class elements in the derived class. Shadowing and
overriding are both available for this purpose.
Comparison
It is easy
to confuse shadowing with overriding. Both are used when a derived class
inherits from a base class, and both redefine one declared element with
another. But there are significant differences between the two.The following
table compares shadowing with overriding.
Point of
comparison Shadowing OverridingPurposeShadowing
Protecting
against a subsequent base class modification that introduces a member you have
already defined in your derived classAchieving polymorphism by defining a
different implementation of a procedure or property with the same calling
sequence1Redefined elementShadowing
Any
declared element typeOnly a procedure (Function, Sub, or Operator) or
propertyRedefining elementShadowing
Any
declared element typeOnly a procedure or property with the identical calling
sequence1Access level of redefining elementShadowing
Any access
levelCannot change access level of overridden elementReadability and
writability of redefining elementShadowing
Any
combinationCannot change readability or writability of overridden
propertyControl over redefiningShadowing
Base class
element cannot enforce or prohibit shadowingBase class element can specify
MustOverride, NotOverridable, or OverridableKeyword usageShadowing
Shadows
recommended in derived class; Shadows assumed if neither Shadows nor Overrides
specified2Overridable or MustOverride required in base class; Overrides
required in derived classInheritance of redefining element by classes deriving
from your derived classShadowing
Shadowing
element inherited by further derived classes; shadowed element still
hidden3Overriding element inherited by further derived classes; overridden
element still overridden
1 The
calling sequence consists of the element type (Function, Sub, Operator, or
Property), name, parameter list, and return type. You cannot override a
procedure with a property, or the other way around. You cannot override one
kind of procedure (Function, Sub, or Operator) with another kind.
2 If you
do not specify either Shadows or Overrides, the compiler issues a warning
message to help you be sure which kind of redefinition you want to use. If you
ignore the warning, the shadowing mechanism is used.
3 If the
shadowing element is inaccessible in a further derived class, shadowing is not
inherited. For example, if you declare the shadowing element as Private, a
class deriving from your derived class inherits the original element instead of
the shadowing element.
36. Should
I make my destructor virtual?
C#
destructor is really just an override of the System.Object Finalize method, and
so is virtual by definition
37. Are C#
destructors the same as C++ destructors?
No. They
look the same but they are very different. The C# destructor syntax (with the
familiar ~ character) is just syntactic sugar for an override of the
System.Object Finalize method. This Finalize method is called by the garbage
collector when it determines that an object is no longer referenced, before it
frees the memory associated with the object. So far this sounds like a C++
destructor. The difference is that the garbage collector makes no guarantees
about when this procedure happens. Indeed, the algorithm employed by the CLR
garbage collector means that it may be a long time after the application has
finished with the object. This lack of certainty is often termed
‘non-deterministic finalization’, and it means that C# destructors are not
suitable for releasing scarce resources such as database connections, file
handles etc.To achieve deterministic destruction, a class must offer a method
to be used for the purpose. The standard approach is for the class to implement
the IDisposable interface. The user of the object must call the Dispose()
method when it has finished with the object. C# offers the ‘using’ construct to
make this easier.
38. Are C#
constructors the same as C++ constructors?
Very
similar, but there are some significant differences. First, C# supports
constructor chaining. This means one constructor can call another:
class Person
{
public Person( string name, int
age ) { … }
public Person( string name ) :
this( name, 0 ) {}
public Person() : this(
"", 0 ) {}
}
Another
difference is that virtual method calls within a constructor are routed to the
most derived implementationError handling is also somewhat different. If an
exception occurs during construction of a C# object, the destuctor (finalizer)
will still be called. This is unlike C++ where the destructor is not called if
construction is not completed.Finally, C# has static constructors. The static
constructor for a class runs before the first instance of the class is
created.Also note that (like C++) some C# developers prefer the factory method
pattern over constructors.
39. Can
you declare a C++ type destructor in C# like ~MyClass()?
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.
40. What
are the fundamental differences between value types and reference types?
C# divides
types into two categories – value types and reference types. Most of the
intrinsic types (e.g. int, char) are value types. Structs are also value types.
Reference types include classes, arrays and strings. The basic idea is
straightforward – an instance of a value type represents the actual data,
whereas an instance of a reference type represents a pointer or reference to
the data.The most confusing aspect of this for C++ developers is that C# has
predetermined which types are represented as values, and which are represented
as references. A C++ developer expects to take responsibility for this
decision.For example, in C++ we can do this:
int x1 = 3; // x1 is a value on
the stack
int *x2 = new int(3) // x2 is a
pointer to a value on the heapbut in C# there is no control:int x1 = 3; // x1
is a value on the stack
int x2 = new int();
x2 = 3; // x2 is also a value on
the stack!
41.How do
you handle errors in VB.NET and C#?
C# and
VB.NET use structured error handling (unlike VB6 and earlier versions where
error handling was implemented using Goto statement). Error handling in both
VB.NET and C# is implemented using Try..Catch..Finally construct (C# uses lower
case construct – try…catch…finally).
42. What
is the purpose of the finally block?
The code
in finally block is guaranteed to run, irrespective of whether an error occurs
or not. Critical portions of code, for example release of file handles or
database connections, should be placed in the finally block.
43. Can I
use exceptions in C#?
Yes, in
fact exceptions are the recommended error-handling mechanism in C# (and in .NET
in general). Most of the .NET framework classes use exceptions to signal
errors.
44. Why is
it a bad idea to throw your own exceptions?
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.
45. 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 {}
46. How to
declare a two-dimensional array in C#?
Syntax for
Two Dimensional Array in C Sharp is int[,] ArrayName;
47.How can
you sort the elements of the array in descending order?
Using
Array.Sort() and Array.Reverse() methods.
int[] arr = new int[3];
arr[0] = 4;
arr[1] = 1;
arr[2] = 5;
Array.Sort(arr);
Array.Reverse(arr);
48. What’s
the difference between the System.Array.CopyTo() and System.Array.Clone()?
The
Clone() method returns a new array (a shallow copy) object containing all the
elements in the original array. The CopyTo() method copies the elements into
another existing array. Both perform a shallow copy. A shallow copy means the
contents (each array element) contains references to the same object as the
elements in the original array. A deep copy (which neither of these methods
performs) would create a new instance of each element’s object, resulting in a
different, yet identacle object.
49.
Structs are largely redundant in C++.Why does C# have them?
In C++, a
struct and a class are pretty much the same thing. The only difference is the
default visibility level (public for structs, private for classes). However, in
C# structs and classes are very different. In C#, structs are value types
(instances stored directly on the stack, or inline within heap-based objects),
whereas classes are reference types (instances stored on the heap, accessed
indirectly via a reference). Also structs cannot inherit from structs or
classes, though they can implement interfaces. Structs cannot have destructors.
A C# struct is much more like a C struct than a C++ struct.
50. 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
51. Where
we can use DLL made in C#.Net?
Supporting
.Net, because DLL made in C#.Net semi compiled version. It’s not a com object.
It is used only in .Net Framework As it is to be compiled at runtime to byte
code.
52. If
A.equals(B) is true then A.getHashcode & B.gethashcode must always return
same hash code.
The answer
is False because it is given that A.equals(B) returns true i.e. objects are
equal and now its hashCode is asked which is always independent of the fact
that whether objects are equal or not. So, GetHashCode for both of the objects
returns different value.
53.Is it
possible to debug the classes written in other .Net languages in a C# project?
It is
definitely possible to debug other .Net languages code in a C# project. As
everyone knows .net can combine code written in several .net languages into one
single assembly. Same is true with debugging.
54. Does
C# has its own class library?
Not
exactly. The .NET Framework has a comprehensive class library, which C# can
make use of. C# does not have its own class library.
55. 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.
56. Is it
possible to restrict the scope of a field/method of a class to the classes in
the same namespace?
There is
no way to restrict to a namespace. Namespaces are never units of protection.
But if you’re using assemblies, you can use the ‘internal’ access modifier to
restrict access to only within the assembly.
57. Is
there an equivalent of exit() or quiting 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.
58. What
optimization 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.
59. Does
C# support multiple inheritance?
No, use
interfaces instead.
60. 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.
61. What
happens when you encounter a continue statement inside for loop?
The code
for the rest of the loop is ignored, the control is transferred back to the
beginning of the loop.
62. Write
one code example for compile time binding and one for run time binding?what is
early/late binding? An object is early bound when it is assigned to a variable
declared to be of a specific object type . Early bound objects allow the
compiler to allocate memory and perform other optimizations before an
application executes.
‘ Create a variable to hold a new
object.
Dim FS As FileStream
‘ Assign a new object to the
variable.
FS = New FileStream("C:\tmp.txt",
FileMode.Open)
By contrast, an object is late
bound when it is assigned to a variable declared to be of type Object. Objects
of this type can hold references to any object, but lack many of the advantages
of early-bound objects.
Dim xlApp As Object
xlApp =
CreateObject("Excel.Application")
|
Question
|
Subject
|
Category
|
|
Java
|
||
|
Other
|
||
|
C#
|
||
|
C#
|
||
|
C#
|
||
|
SQL Server
|
||
|
.NET Framework
|
||
|
SQL Server
|
||
|
SQL Server
|
||
|
SQL Server
|
||
|
SQL Server
|
||
|
SQL Server
|
||
|
SQL Server
|
||
|
C#
|
||
|
ASP.NET
|
||
|
SQL Server
|
||
|
SQL Server
|
||
|
SQL Server
|
||
|
SQL Server
|
||
|
SQL Server
|
||
|
SQL Server
|
||
|
.NET Framework
|
||
|
.NET Framework
|
||
|
.NET Framework
|
||
|
.NET Framework
|
||
|
.NET Framework
|
||
|
C#
|
||
|
C#
|
||
|
C#
|
||
|
Other
|
||
|
C#
|
||
|
C#
|
||
|
C#
|
||
|
C#
|
||
|
C#
|
||
|
C#
|
||
|
C#
|
||
|
C#
|
||
|
C#
|
||
|
C#
|
||
|
C#
|
||
|
C#
|
||
|
C#
|
||
|
C#
|
||
|
C#
|
||
|
C#
|
||
|
C#
|
||
|
C#
|
||
|
C#
|
||
|
C#
|
C# .NET interview questions
Good for preparation and general
self-testing, but too specific for the actual job interview. This was sent in
by a job applicant getting ready to step into the .NET field in India.
- 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.
- Why does DllImport not work
for me? - All methods marked with the
DllImport attribute must be marked as public static extern.
- 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.
- 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)
- Why do I get a syntax error
when trying to declare a variable called checked? - The word checked is a keyword in C#.
- 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.
- 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 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.
- 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() {} }
- What is the equivalent to
regsvr32 and regsvr32 /u a file in .NET development? - Try using RegAsm.exe. Search MSDN on Assembly Registration Tool.
- 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.
- 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#:
13.
switch(x)
14.
{
15.
case 0: // do something
16.
case 1: // do something as
continuation of case 0
17.
default: // do something in common
with
18.
//0, 1 and everything else
19.
break;
20.
}
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;
}
}
}
- Is there regular expression
(regex) support available to C# developers? -
Yes. The .NET class libraries provide support for regular expressions.
Look at the System.Text.RegularExpressions
namespace.
- Is there any sample C# code
for simple threading? -
Yes:
23.
using System;
24.
using System.Threading;
25.
class ThreadTest
26.
{
27.
public void runme()
28.
{
29.
Console.WriteLine("Runme
Called");
30.
}
31.
public static void Main(String[]
args)
32.
{
33.
ThreadTest b = new ThreadTest();
34.
Thread t = new Thread(new
ThreadStart(b.runme));
35.
t.Start();
36.
}
}
- 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.
- 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().
- 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:
40.
using System;
41.
class BreakExample
42.
{
43.
public static void Main(String[]
args) {
44.
for(int i=0; i<3; i++)
45.
{
46.
Console.WriteLine("Pass {0}:
", i);
47.
for( int j=0 ; j<100 ; j++ )
48.
{
49.
if ( j == 10)
50.
goto done;
51.
Console.WriteLine("{0} ",
j);
52.
}
53.
Console.WriteLine("This will
not print");
54.
}
55.
done:
56.
Console.WriteLine("Loops
complete.");
57.
}
}
- Is it possible to restrict
the scope of a field/method of a class to the classes in the same
namespace? - There is no way to restrict
to a namespace. Namespaces are never units of protection. But if you’re
using assemblies, you can use the ‘internal’ access modifier to restrict
access to only within the assembly.
59.
What is
the Microsoft.NET?
60.
.NET is a set of technologies
designed to transform the internet into a full scale distributed platform. It
provides new ways of connecting systems, information and devices through a
collection of web services. It also provides a language independent, consistent
programming model across all tiers of an application.
61.
The goal of the .NET platform is to
simplify web development by providing all of the tools and technologies that
one needs to build distributed web applications.
62.
What is
the .NET Framework?
63.
The .NET Framework is set of
technologies that form an integral part of the .NET Platform. It is Microsoft's
managed code programming model for building applications that have visually
stunning user experiences, seamless and secure communication, and the ability
to model a range of business processes.
64.
The .NET Framework has two main
components: the common language runtime (CLR) and .NET Framework class library.
The CLR is the foundation of the .NET framework and provides a common set of
services for projects that act as building blocks to build up applications
across all tiers. It simplifies development and provides a robust and
simplified environment which provides common services to build application. The
.NET framework class library is a collection of reusable types and exposes
features of the runtime. It contains of a set of classes that is used to access
common functionality.
65.
What is
CLR?
66.
The .NET Framework provides a runtime
environment called the Common Language Runtime or CLR. The CLR can be compared
to the Java Virtual Machine or JVM in Java. CLR handles the execution of code
and provides useful services for the implementation of the program. In addition
to executing code, CLR provides services such as memory management, thread
management, security management, code verification, compilation, and other
system services. It enforces rules that in turn provide a robust and secure
execution environment for .NET applications.
67.
What is
CTS?
68.
Common Type System (CTS) describes
the datatypes that can be used by managed code. CTS defines how these types are
declared, used and managed in the runtime. It facilitates cross-language
integration, type safety, and high performance code execution. The rules
defined in CTS can be used to define your own classes and values.
69.
What is
CLS?
70.
Common Language Specification (CLS)
defines the rules and standards to which languages must adhere to in order to
be compatible with other .NET languages. This enables C# developers to inherit
from classes defined in VB.NET or other .NET compatible languages.
71.
What is
managed code?
72.
The .NET Framework provides a
run-time environment called the Common Language Runtime, which manages the
execution of code and provides services that make the development process
easier. Compilers and tools expose the runtime's functionality and enable you
to write code that benefits from this managed execution environment. The code
that runs within the common language runtime is called managed code.
73.
What is
MSIL?
74.
When the code is compiled, the
compiler translates your code into Microsoft intermediate language (MSIL). The
common language runtime includes a JIT compiler for converting this MSIL then
to native code.
75.
MSIL contains metadata that is the
key to cross language interoperability. Since this metadata is standardized
across all .NET languages, a program written in one language can understand the
metadata and execute code, written in a different language. MSIL includes
instructions for loading, storing, initializing, and calling methods on
objects, as well as instructions for arithmetic and logical operations, control
flow, direct memory access, exception handling, and other operations.
76.
What is
JIT?
77.
JIT is a compiler that converts MSIL
to native code. The native code consists of hardware specific instructions that
can be executed by the CPU.
78.
Rather than converting the entire
MSIL (in a portable executable[PE]file) to native code, the JIT converts the
MSIL as it is needed during execution. This converted native code is stored so
that it is accessible for subsequent calls.
79.
What is
portable executable (PE)?
PE is the file format defining the structure that all executable files (EXE) and Dynamic Link Libraries (DLL) must use to allow them to be loaded and executed by Windows. PE is derived from the Microsoft Common Object File Format (COFF). The EXE and DLL files created using the .NET Framework obey the PE/COFF formats and also add additional header and data sections to the files that are only used by the CLR.
PE is the file format defining the structure that all executable files (EXE) and Dynamic Link Libraries (DLL) must use to allow them to be loaded and executed by Windows. PE is derived from the Microsoft Common Object File Format (COFF). The EXE and DLL files created using the .NET Framework obey the PE/COFF formats and also add additional header and data sections to the files that are only used by the CLR.
80.
What is an
application domain?
81.
Application domain is the boundary
within which an application runs. A process can contain multiple application
domains. Application domains provide an isolated environment to applications
that is similar to the isolation provided by processes. An application running
inside one application domain cannot directly access the code running inside
another application domain. To access the code running in another application
domain, an application needs to use a proxy.
82.
How does
an AppDomain get created?
AppDomains are usually created by hosts. Examples of hosts are the Windows Shell, ASP.NET and IE. When you run a .NET application from the command-line, the host is the Shell. The Shell creates a new AppDomain for every application. AppDomains can also be explicitly created by .NET applications.
AppDomains are usually created by hosts. Examples of hosts are the Windows Shell, ASP.NET and IE. When you run a .NET application from the command-line, the host is the Shell. The Shell creates a new AppDomain for every application. AppDomains can also be explicitly created by .NET applications.
83.
What is an
assembly?
84.
An assembly is a collection of one
or more .exe or dll’s. An assembly is the fundamental unit for application
development and deployment in the .NET Framework. An assembly contains a
collection of types and resources that are built to work together and form a
logical unit of functionality. An assembly provides the CLR with the
information it needs to be aware of type implementations.
85.
What are
the contents of assembly?
86.
A static assembly can consist of
four elements:
87. Assembly
manifest - Contains the assembly metadata. An assembly manifest contains the
information about the identity and version of the assembly. It also contains
the information required to resolve references to types and resources.
88. Type
metadata - Binary information that describes a program.
89. Microsoft
intermediate language (MSIL) code.
90.
A set of resources.
91.
What are
the different types of assembly?
92.
Assemblies can also be private or
shared. A private assembly is installed in the installation directory of an
application and is accessible to that application only. On the other hand, a
shared assembly is shared by multiple applications. A shared assembly has a strong
name and is installed in the GAC.
93.
We also have satellite assemblies
that are often used to deploy language-specific resources for an application.
94.
What is a
dynamic assembly?
95.
A dynamic assembly is created
dynamically at run time when an application requires the types within these
assemblies.
96.
What is a
strong name?
You need to assign a strong name to an assembly
to place it in the GAC and make it globally accessible. A strong name consists
of a name that consists of an assembly's identity (text name, version number,
and culture information), a public key and a digital signature
No comments:
Post a Comment