Вы находитесь на странице: 1из 19

c# interview questions

.net interview questions

what�s the implicit name of the parameter that gets passed into the class� set
method?
value, and it�s datatype depends on whatever variable we�re changing.

how do you inherit from a class in c#?


place a colon and then the name of the base class.

does c# support multiple inheritance?


no, use interfaces instead.
when you inherit a protected class-level variable, who is it available to?
classes in the same namespace.
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.
describe the accessibility modifier protected internal. it�s available to derived
classes and classes within the same assembly (and naturally from the base class
it�s declared in).
c# provides a default constructor for me. i write a constructor that takes a
string as a parameter, but want to keep the no parameter one. how many
constructors should i write? two. once you write at least one constructor, c#
cancels the freebie constructor, and now you have to write one yourself, even if
there�s no implementation in it.

what�s the top .net class that everything is derived from?


system.object.

how�s 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.
what does the keyword virtual mean in the method definition?
the method can be over-ridden.

can you declare the override method static while the original method is non-
static?
no, you can�t, the signature of the virtual method must remain the same, only the
keyword virtual is changed to keyword override.
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.
can you prevent your class from being inherited and becoming a base class for some
other classes?
yes, that�s what keyword sealed in the class definition is for. the developer
trying to derive from your class will get a message: cannot inherit from sealed
class whateverbaseclassname. it�s the same concept as final class in java.
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.
what�s 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�s a blueprint for a class without any implementation.
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�s an interface class? it�s an abstract class with public abstract methods all
of which must be implemented in the inherited classes.
why can�t 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�s public by default.
can you inherit multiple interfaces?
yes, why not.
and if 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.
what�s 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.
how can you overload a method?
different parameter data types, different number of parameters, different order
of parameters.
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.

what�s 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.

is it namespace class or class namespace?


the .net class library is organized into namespaces.
each namespace contains a functionally related group of classes so natural
namespace comes first.

==================================================================================
==

==================================================================================
=========

.net classes used :

1.1 what is c#?


c# is a programming language designed by microsoft. it is loosely based on c/c++,
and bears a striking similarity to java in many ways. microsoft describe c# as
follows:
"c# is a simple, modern, object oriented, and type-safe programming language
derived from c and c++. c# (pronounced 'c sharp') is firmly planted in the c and
c++ family tree of languages, and will immediately be familiar to c and c++
programmers. c# aims to combine the high productivity of visual basic and the raw
power of c++."
1.2 how do i develop c# apps?
the (free) .net sdk contains the c# command-line compiler (csc.exe). visual
studio.net has fully integrated support for c# development.
1.3 where can i download the .net sdk & visual studio.net?
you can download the sdk from http://msdn.microsoft.com/net. if you are an msdn
universal subscriber, you can also download visual studio.net.
1.4 does c# replace java?
c# is a very java-like language - the core of both languages have similar
advantages and limitations when compared to c++. for example, both languages have
garbage collection, but neither language has templates. microsoft have ceased
production of visual j++, so it's hard not to view c# as microsoft's alternative
to java.
1.5 does c# replace c++?
the obvious answer is no. however it's difficult to see c++ as the best choice for
new .net code. for the .net runtime to function fully, it requires the programming
language to conform to certain rules - one of these rules is that language types
must conform to the common type system (cts). unfortunately many c++ features are
not supported by the cts - for example multiple inheritance of classes and
templates.
microsoft's answer to this problem is to offer managed extensions (me) for c++,
which allows you to write c++ that conforms to the cts. new keywords are provided
to mark your c++ classes with cts attributes (e.g. __gc for garbage collection).
however, it's difficult to see why me c++ would be chosen over c# for new
projects. in terms of features they are very similar, but unlike c++, c# has been
designed from the ground-up to work seamlessly with the .net environment. the
raison d'etre for me c++ would therefore appear to be porting existing c++ code to
the .net environment.
so, in answer to the question, my suspicion is that c++ will remain an important
language outside of the .net environment, and will be used (via me) to port
existing code to .net, but i think c# will become the language of choice for one-
time c++ developers developing new .net applications. but only time will tell ...
1.6 what does a simple c# program look like?
sorry, my imagination has deserted me. yes, you guessed it, here comes 'hello,
world' ...
class capplication
{
public static void main()
{
system.console.write( "hello, new .net world." );
}
}
(no, you can't put main() as a global function - global functions don't exist in
c#.)
1.7 is c# object-oriented?
yes, c# is an oo language in the tradition of java and c++.
1.8 does c# have its own class library?
not exactly. in common with all .net languages (e.g. visualbasic.net, jscript.net)
c# has access to the .net class library. c# does not have its own class library.
2. basic types
2.1 what standard types does c# supply?
c# supports a very similar range of basic types to c++, including int, long,
float, double, char, string, arrays, structs and classes. however, don't assume
too much. the names may be familiar, but some 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#.
2.2 is it true that all c# types derive from a common base class?
yes and no. all types can be treated as if they derive from object
(system.object), but in order to treat an instance of a value type (e.g. int,
float) as object-derived, the instance must be converted to a reference type using
a process called 'boxing'. in theory a developer can forget about this and let the
run-time worry about when the conversion is necessary, but in reality this
implicit conversion can have side-effects that may trip up the unwary.
2.3 so this means i can pass an instance of a value type to a methodthat takes an
object as a parameter?
yes. for example:
class capplication
{
public static void main()
{
int x = 25;
string s = "fred";

displayme( x );
displayme( s );
}

static void displayme( object o )


{
system.console.writeline( "you are {0}", o );
}
}
this would display:
you are 25
you are fred

2.4 what are the fundamental differences between value types andreference types?
c# divides types into two categories - value types and reference types. most of
the basic intrinsic types (e.g. int, char) are value types. structs are also value
types. reference types include classes, interfaces, arrays and strings. the basic
idea is straightforward - an instance of a value type represents the actual data
(stored on the stack), whereas an instance of a reference type represents a
pointer or reference to the data (stored on the heap).
the most confusing aspect of this for c++ developers is that c# has predetermined
which types will be represented as values, and which will be 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 reference to a value on the heap
but 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!
2.5 okay, so an int is a value type, and a class is areference type. how can int
be derived from object?
it isn't, really. when an int is being used as an int, it is a value (on the
stack). however, when it is being used as an object, it is a reference to an
integer value on the heap. in other words, when you treat an int as an object, the
runtime automatically converts the int value to an object reference. this process
is called boxing. the conversion involves copying the contents of the int from the
stack to the heap, and creating an object instance which refers to it. unboxing is
the reverse process - the object is converted back to a stack-based value.
int x = 3; // new int value 3 on the stack
object objx = x; // new int on heap, set to value 3 - still have x=3 on stack
int y = (int)objx; // new value 3 on stack, still got x=3 on stack and objx=3 on
heap
2.6 c# uses references instead of pointers. are c# references the sameas c++
references?
not quite. the basic idea is the same, but one significant difference is that c#
references can be null . so you cannot rely on a c# reference pointing to a valid
object. if you try to use a null reference, a nullreferenceexception is thrown.
for example, look at the following method:
void displaystringlength( string s )
{
console.writeline( "string is length {0}", s.length );
}
the problem with this method is that it will throw a nullreferenceexception if
called like this:
string s = null;
displaystringlength( s );
of course for some situations you may deem a nullreferenceexception to be a
perfectly acceptable outcome, but in this case it might be better to re-write the
method like this:
void displaystringlength( string s )
{
if( s == null )
console.writeline( "string is null" );
else
console.writeline( "string is length {0}", s.length );
}
3. classes and structs
3.1 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 (stored on the stack), whereas classes are reference types (stored on the
heap). also structs cannot inherit from structs or classes, though they can
implement interfaces. structs cannot have destructors.
3.2 does c# support multiple inheritance (mi)?
c# supports multiple inheritance of interfaces, but not of classes.
3.3 is a c# interface the same as a c++ abstract class?
no, not quite. an abstract class in c++ cannot be instantiated, but it can (and
often does) contain implementation code and/or data members. a c# interface cannot
contain any implementation code or data members - it is simply a group of method
names & signatures. a c# interface is more like a com interface than a c++
abstract class.
the other major difference is that a c# class can inherit from only one class
(abstract or not), but can implement multiple interfaces.
3.4 are c# constructors the same as c++ constructors?
very similar.
3.5 are c# destructors the same as c++ destructors?
no! they look the same but they're very different. first of all, a c# destructor
isn't guaranteed to be called at any particular time. in fact it's not guaranteed
to be called at all. truth be told, a c# destructor is really just a finalize
method in disguise. in particular, it is a finalize method with a call to the base
class finalize method inserted. so this:
class ctest
{
~ctest()
{
system.console.writeline( "bye bye" );
}
}
is really this:
class ctest
{
protected override void finalize()
{
system.console.writeline( "bye bye" );
base.finalize();
}
}
with the arrival of beta 2, explicitly overriding finalize() like this is not
allowed - the destructor syntax must be used.
3.6 if c# destructors are so different to c++ destructors, why did msuse the same
syntax?
because they're evil, and they want to mess with your mind.
3.7 what is a static constructor?
a constructor for a class, rather than instances of a class. the static
constructor is called when the class is loaded.
3.8 are all methods virtual in c#?
no. like c++, methods are non-virtual by default, but can be marked as virtual.
3.9 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).
4. exceptions
4.1 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.
4.2 what types of object can i throw as exceptions?
only instances of the system.exception classes, or classes derived from
system.exception. this is in sharp contrast with c++ where instances of almost any
type can be thrown.
4.3 can i define my own exceptions?
yes, as long as you follow the rule that exceptions derive from system.exception.
more specifically, ms recommend that user-defined exceptions inherit from
system.applicationexception (which is derived from system.exception).
4.4 are there any standard exceptions that i can re-use?
yes, and some of them loosely correspond to standard com hresults. the table below
shows a mapping from hresults to .net (and therefore c#) exceptions:
hresult .net exception
e_invalidarg argumentoutofrangeexception, or the more general argumentexception.
alternatively formatexception if a supplied parameter is not the correct format -
e.g. a url is specified as htp:// instead of http://
e_pointer argumentnullexception
e_notimpl notimplementedexception
e_unexpected some may consider invalidoperationexception to be equivalent.
invalidoperationexception is normally used to indicate that an object cannot
perform the requested operation because it is not in a suitable state to do so.
e_outofmemory outofmemoryexception
other standard exceptions that you might want to re-use are
indexoutofrangeexception and arithmeticexception .
4.5 does the system.exception class have any cool features?
yes - the feature which stands out is the stacktrace property. this provides a
call stack which records where the exception was thrown from. for example, the
following code:
using system;

class capp
{
public static void main()
{
try
{
f();
}
catch( exception e )
{
console.writeline( "system.exception stack trace = \n{0}", e.stacktrace );
}
}

static void f()


{
throw new exception( "f went pear-shaped" );
}
}
produces this output:
system.exception stack trace =
at capp.f()
at capp.main()
note, however, that this stack trace was produced from a debug build. a release
build may optimise away some of the method calls which could mean that the call
stack isn't quite what you expect.
4.6 when should i throw an exception?
this is the subject of some debate, and is partly a matter of taste. however, it
is accepted by many that exceptions should be thrown only when an 'unexpected'
error occurs. how do you decide if an error is expected or unexpected? this is a
judgement call, but a straightforward example of an expected error is failing to
read from a file because the seek pointer is at the end of the file, whereas an
example of an unexpected error is failing to allocate memory from the heap.
4.7 does c# have a 'throws' clause?
no, unlike java, c# does not require (or even allow) the developer to specify the
exceptions that a method can throw.
5. run-time type information
5.1 how can i check the type of an object at runtime?
you can use the is keyword. for example:
using system;

class capp
{
public static void main()
{
string s = "fred";
long i = 10;

console.writeline( "{0} is {1}an integer", s, (isinteger(s) ? "" : "not ") );


console.writeline( "{0} is {1}an integer", i, (isinteger(i) ? "" : "not ") );
}

static bool isinteger( object obj )


{
if( obj is int || obj is long )
return true;
else
return false;
}
}
produces the output:
fred is not an integer
10 is an integer
5.2 can i get the name of a type at runtime?
yes, use the gettype method of the object class (which all types inherit from).
for example:
using system;

class ctest
{
class capp
{
public static void main()
{
long i = 10;
ctest ctest = new ctest();

displaytypeinfo( ctest );
displaytypeinfo( i );
}

static void displaytypeinfo( object obj )


{
console.writeline( "type name = {0}, full type name = {1}", obj.gettype(),
obj.gettype().fullname );
}
}
}
produces the following output:
type name = ctest, full type name = ctest
type name = int64, full type name = system.int64
6. advanced language features
6.1 what are delegates?
a delegate is a class derived from system.delegate. however the language has a
special syntax for declaring delegates which means that they don't look like
classes. a delegate represents a method with a particular signature. an instance
of a delegate represents a method with a particular signature on a particular
object (or class in the case of a static method). for example:
using system;
delegate void stereotype();

class camerican
{
public void bepatriotic()
{
console.writeline( "... ... god bless america.");
}
}

class cbrit
{
public void bexenophobic()
{
console.writeline( "bloody foreigners ... " );
}
}

class capplication
{
public static void revealyourstereotype( stereotype[] stereotypes )
{
foreach( stereotype s in stereotypes )
s();
}

public static void main()


{
camerican chuck = new camerican();
cbrit edward = new cbrit();

// create our list of sterotypes.


stereotype[] stereotypes = new stereotype[2];
stereotypes[0] = new stereotype( chuck.bepatriotic );
stereotypes[1] = new stereotype( edward.bexenophobic );

// reveal yourselves!
revealyourstereotype(stereotypes );
}
}
this produces the following result:
... ... god bless america.
bloody foreigners ...
6.2 are delegates just like interfaces with a single method?
conceptually delegates can be used in a similar way to an interface with a single
method. the main practical difference is that with an interface the method name is
fixed, whereas with a delegate only the signature is fixed - the method name can
be different, as shown in the example above.
6.3 what is the c# equivalent of queryinterface?
the as keyword. for example:
using system;

interface iperson
{
string getname();
}

interface iperson2 : iperson


{
int getage();
}

class cperson : iperson


{
public cperson( string name )
{
m_name = name;
}

// iperson
public string getname()
{
return m_name;
}

private string m_name;


}

class cperson2 : iperson2


{
public cperson2( string name, int age )
{
m_name = name;
m_age = age;
}

// iperson2
public string getname() { return m_name; }
public int getage() { return m_age; }
private string m_name; private int m_age;
}

public class capp


{
public static void main()
{
cperson bob = new cperson( "bob" );
cperson2 sheila = new cperson2( "sheila", 24 );

displayage( bob );
displayage( sheila );
}

static void displayage( iperson person )


{
iperson2 person2 = person as iperson2; // queryinterface lives on !!!
if( person2 != null )
console.writeline( "{0} is {1} years old.", person2.getname(), person2.getage() );

else
console.writeline( "sorry, don't know {0}'s age.", person.getname() );
}
}
running the program produces the following output:
sorry, don't know bob's age.
sheila is 24 years old.
7. it doesn't work like that in c++ ...
7.1 i 'new'-ed an object, but how do i delete it?
you can't. you are not allowed to call the destructor explicitly, and no delete
operator is provided. don't worry, the garbage collector will destroy your object
.... eventually .... probably .... :-)
7.2 i tried to create an object on the stack, but the c# compilercomplained.
what's going on?
unlike c++, you cannot create instances of classes on the stack. class instances
always live on the heap and are managed by the garbage collector.
7.3 i defined a destructor, but it never gets called. why?
a c# destructor is really just an implementation of finalize, and the runtime
doesn't guarantee to call finalize methods. the semantics of a c# destructor are
quite different from a c++ destructor.
7.4 most of the c# basic types have the same names as c++ basic types?are they the
same?
no. a char in c# is equivalent to a wchar_t in c++. all characters (and strings,
obviously) are unicode in c#. integral values in c# are concrete sizes, unlike c++
(where size depends on processor). for example, a c# int is 32 bits, whereas a c++
int is normally 32 bits on a 32-bit processor and 64 bits on a 64-bit processor. a
c# long is 64 bits.
8. miscellaneous
8.1 string comparisons using == seem to be case-sensitive? how do i doa case-
insensitive string comparison?
use the string.compare function. its third parameter is a boolean which specifies
whether case should be ignored or not.
"fred" == "fred" // false
system.string.compare( "fred", "fred", true ) // true
8.2 i've seen some string literals which use the @ symbol, and somewhich don't.
what's that all about?
the @ symbol before a string literal means that escape sequences are ignored. this
is particularly useful for file names, e.g.
string filename = "c:\\temp\\test.txt"
versus:
string filename = @"c:\temp\test.txt"
8.3 does c# support a variable number of arguments?
yes, using the params keyword. the arguments are specified as a list of arguments
of a specific type, e.g. int. for ultimate flexibility, the type can be object.
the standard example of a method which uses this approach is
system.console.writeline().
8.4 how can i process command-line arguments?
like this:
using system;

class capp
{
public static void main( string[] args )
{
console.writeline( "you passed the following arguments:" );
foreach( string arg in args )
console.writeline( arg );
}
}
8.5 does c# do array bounds checking?
yes. an indexoutofrange exception is used to signal an error.
8.6 how can i make sure my c# classes will interoperate with other .netlanguages?
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.

======================================================================

==================================================================================
=

===========================================================================

c# interview questions
this is a list of questions i have gathered from other sources and created myself
over a period of time from my experience, many of which i felt where incomplete or
simply wrong. i have finally taken the time to go through each question and
correct them to the best of my ability. however, please feel free to post
feedback to challenge, improve, or suggest new questions. i want to thank those
of you that have contributed quality questions and corrections thus far.

there are some question in this list that i do not consider to be good questions
for an interview. however, they do exist on other lists available on the internet
so i felt compelled to keep them easy access.

general questions

does c# support multiple-inheritance?


no.

who is a protected class-level variable available to?


it is available to any sub-class (a class inheriting this class).

are private class-level variables inherited?


yes, but they are not accessible. although they are not visible or accessible via
the class interface, they are inherited.

describe the accessibility modifier �protected internal�.


it is available to classes that are within the same assembly and derived from the
specified base class.

what�s the top .net class that everything is derived from?


system.object.

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.

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.

what�s the advantage of using system.text.stringbuilder over system.string?


stringbuilder is more efficient in cases where there is a large amount of string
manipulation. strings are immutable, so each time a string is changed, a new
instance in memory 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 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.

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.

what class is underneath the sortedlist class?


a sorted hashtable.

will the finally block get executed if an exception has not occurred?�
yes.

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

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

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

class questions

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.

what�s 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.

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.

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.

why can�t you specify the accessibility modifier for methods inside the interface?
they all must be public, and are therefore public by default.

can you inherit multiple interfaces?


yes. .net does support multiple interfaces.

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

what is the difference between a struct and a class?


structs are value-type variables and are thus saved on the stack, additional
overhead but faster retrieval. another difference is that structs cannot inherit.

method and property questions

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 does the keyword �virtual� declare for a method or property?


the method or property can be overridden.

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.

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)

what are the different ways a method can be overloaded?


different parameter data types, different number of parameters, different order of
parameters.

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.

events and delegates

what�s a delegate?
a delegate object encapsulates a reference to a method.

what�s a multicast delegate?


a delegate that has multiple handlers assigned to it. each assigned handler
(method) is called.
xml documentation questions

is xml case-sensitive?
yes.

what�s the difference between // comments, /* */ comments and /// comments?


single-line comments, multi-line comments, and xml documentation comments.

how do you generate documentation from the c# file commented properly with a
command-line compiler?
compile it with the /doc switch.

debugging and testing questions

what debugging tools come with the .net sdk?


1. cordbg � command-line debugger. to use cordbg, you must compile the original
c# file using the /debug switch.
2. dbgclr � graphic debugger. visual studio .net uses the dbgclr.

what does assert() method 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. 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.

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

ado.net and database questions

what is the role of the datareader class in ado.net connections?


it returns a read-only, forward-only rowset from the data source. a datareader
provides fast access when a forward-only sequential read is needed.

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. 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%�.

explain acid rule of thumb for transactions.


a transaction must be:
1. atomic - it is one unit of work and does not dependent on previous and
following transactions.
2. consistent - data is either committed or roll back, no �in-between� case
where something has been updated and something hasn�t.
3. isolated - no transaction sees the intermediate results of the current
transaction).
4. 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 password).

between windows authentication and sql server authentication, 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.

what does the initial catalog parameter define in the connection string?
the database name to connect to.

what does the dispose method do with the connection object?


deletes it from the memory.
to do: answer better. the current answer is not entirely correct.

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. the connection
string must be identical.

assembly questions

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.

what are the ways to deploy an assembly?


an msi installer, a cab archive, and xcopy command.

what is 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 and system.resources.

what is the smallest unit of execution in .net?


an assembly.

when should you call the garbage collector in .net?


as a good rule, you should not call the garbage collector. however, you could
call the garbage collector when you are done using a large object (or set of
objects) to force the garbage collector to dispose of those very large objects
from memory. however, this is usually not a good practice.

how do you convert a value-type to a reference-type?


use boxing.

what happens in memory when you box and unbox a value-type?


boxing converts a value-type to a reference-type, thus storing the object on the
heap. unboxing converts a reference-type to a value-type, thus storing the value
on the stack.

===========================================================================

==================================================================================
=======

========
c# and .net interview questions
.net interview questions

how big is the datatype int in .net? 32 bits.

how big is the char? 16 bits (unicode).


how do you initiate a string without escaping each backslash? put an @ sign in
front of the double-quoted string.
what are valid signatures for the main function?
public static void main()
public static int main()
public static void main( string[] args )
public static int main(string[] args )
does main() always have to be public? no.
how do you initialize a two-dimensional array that you don�t know the dimensions
of?
int [, ] myarray; //declaration
myarray= new int [5, 8]; //actual initialization
what�s the access level of the visibility type internal? current assembly.
what�s the difference between struct and class in c#?
structs cannot be inherited.
structs are passed by value, not by reference.
struct is stored on the stack, not the heap.
explain encapsulation. the implementation is hidden, the interface is exposed.
what data type should you use if you want an 8-bit value that�s signed? sbyte.
speaking of boolean data types, what�s different between c# and c/c++? there�s no
conversion between 0 and false, as well as any other number and true, like in
c/c++.
where are the value-type variables allocated in the computer ram? stack.
where do the reference-type variables go in the ram? the references go on the
stack, while the objects themselves go on the heap. however, in reality things are
more elaborate.
what is the difference between the value-type variables and reference-type
variables in terms of garbage collection? the value-type variables are not
garbage-collected, they just fall off the stack when they fall out of scope, the
reference-type objects are picked up by gc when their references go null.
how do you convert a string into an integer in .net? int32.parse(string),
convert.toint32()
how do you box a primitive data type variable? initialize an object with its
value, pass an object, cast it to an object
why do you need to box a primitive variable? to pass it by reference or apply a
method that an object supports, but primitive doesn�t.
what�s the difference between java and .net garbage collectors? sun left the
implementation of a specific garbage collector up to the jre developer, so their
performance varies widely, depending on whose jre you�re using. microsoft
standardized on their garbage collection.
how do you enforce garbage collection in .net? system.gc.collect();
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.
what�s different about namespace declaration when comparing that to package
declaration in java? no semicolon. package declarations also have to be the first
thing within the file, can�t be nested, and affect all classes within the file.
what�s the difference between const and readonly? you can initialize readonly
variables to some runtime values. let�s say your program uses current date and
time as one of the values that won�t change. this way you declare

public readonly string datet = new datetime().tostring().

can you create enumerated data types in c#? yes.


what�s different about switch statements in c# as compared to c++? no fall-
throughs allowed.
what happens when you encounter a continue statement inside the for loop? the code
for the rest of the loop is ignored, the control is transferred back to the
beginning of the loop.
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.
describe the compilation process for .net code? source code is compiled and run in
the .net framework using a two-stage process. first, source code is compiled to
microsoft intermediate language (msil) code using a .net framework-compatible
compiler, such as that for visual basic .net or visual c#. second, msil code is
compiled to native code.
name any 2 of the 4 .net authentification methods. asp.net, in conjunction with
microsoft internet information services (iis), can authenticate user credentials
such as names and passwords using any of the following authentication methods:

windows: basic, digest, or integrated windows authentication (ntlm or kerberos).


microsoft passport authentication
forms authentication
client certificate authentication
how do you turn off sessionstate in the web.config file? in the system.web section
of web.config, you should locate the httpmodule tag and you simply disable session
by doing a remove tag with attribute name set to session.
<httpmodules>
<remove name=�session� />
</httpmodules>

what is main difference between global.asax and web.config? asp.net uses the
global.asax to establish any global objects that your web application uses. the
.asax extension denotes an application file rather than .aspx for a page file.
each asp.net application can contain at most one global.asax file. the file is
compiled on the first page hit to your web application. asp.net is also configured
so that any attempts to browse to the global.asax page directly are rejected.
however, you can specify application-wide settings in the web.config file. the
web.config is an xml-formatted text file that resides in the web site�s root
directory. through web.config you can specify settings like custom 404 error
pages, authentication and authorization settings for the web site, compilation
options for the asp.net web pages, if tracing should be enabled, etc.

==============================================================================

================================================================

Вам также может понравиться