Sei sulla pagina 1di 115

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.


Example: class DerivedClassName: BaseClassName

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

Page 1 of 115
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.

Page 2 of 115
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.
P1.cs
class BC
{
public void Display()
{
System.Console.WriteLine("BC::Display");
}
}
class DC : BC
{
new public void Display()
{
System.Console.WriteLine("DC::Display");

Page 3 of 115
}
}
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.

Page 4 of 115
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.

Page 5 of 115
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.
<modifier> <return type> this [argument list]
{
get
{
// Get codes goes here
}
set
{
// Set codes goes here
}
}
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.)
Eg:Class A
{
public int i;
}
A objA = new A; // A is a .net managed type

Page 6 of 115
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?
Ans.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#?

Page 7 of 115
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

Page 8 of 115
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?

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

Page 9 of 115
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#?

Page 10 of 115
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);

Page 11 of 115
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\”;

Page 12 of 115
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.

Page 13 of 115
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 inheritances?

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

Page 14 of 115
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”)

General Questions
1. Does C# support multiple-inheritance?
No.
2. Who is a protected class-level variable available to?
It is available to any sub-class (a class inheriting this class).
3. 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.
4. Describe the accessibility modifier “protected internal”.
It is available to classes that are within the same assembly and derived from the
specified base class.
5. What’s the top .NET class that everything is derived from?
System.Object.
6. 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.
7. 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.

Page 15 of 115
8. 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.
9. Can you store multiple data types in System.Array?
No.
10. 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.
11. How can you sort the elements of the array in descending order?
By calling Sort() and then Reverse() methods.
12. What’s the .NET collection class that allows an element to be accessed using
a unique key?
HashTable.
13. What class is underneath the SortedList class?
A sorted HashTable.
14. Will the finally block get executed if an exception has not occurred?
Yes.
15. 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 {}.
16. 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).
17. 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).

Page 16 of 115
Class Questions
1. 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
2. Can you prevent your class from being inherited by another class?
Yes. The keyword “sealed” will prevent the class from being inherited.
3. 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.
4. 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.
5. 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.
6. 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.
7. Why can’t you specify the accessibility modifier for methods inside the
interface?
They all must be public, and are therefore public by default.
8. Can you inherit multiple interfaces?
Yes. .NET does support multiple interfaces.
9. 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

Page 17 of 115
10. 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.
11. 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
1. 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.
2. What does the keyword “virtual” declare for a method or property?
The method or property can be overridden.
3. 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.
4. 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)
5. What are the different ways a method can be overloaded?
Different parameter data types, different number of parameters, different order of
parameters.
6. 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

Page 18 of 115
1. What’s a delegate?
A delegate object encapsulates a reference to a method.
2. What’s a multicast delegate?
A delegate that has multiple handlers assigned to it. Each assigned handler
(method) is called.
XML Documentation Questions
1. Is XML case-sensitive?
Yes.
2. What’s the difference between // comments, /* */ comments and /// comments?
Single-line comments, multi-line comments, and XML documentation comments.
3. 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
1. 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.
2. 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.
3. 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.
4. 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.
5. Where is the output of TextWriterTraceListener redirected?
To the Console or a text file depending on the parameter passed to the
constructor.

Page 19 of 115
6. How do you debug an ASP.NET Web application?
Attach the aspnet_wp.exe process to the DbgClr debugger.
7. 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).
8. 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
1. 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.
2. 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.
3. 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%’.
4. 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.

Page 20 of 115
5. What connections does Microsoft SQL Server support?
Windows Authentication (via Active Directory) and SQL Server authentication
(via Microsoft SQL Server username and password).
6. 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.
7. What does the Initial Catalog parameter define in the connection string?
The database name to connect to.
8. 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.
9. 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
1. 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.
2. What are the ways to deploy an assembly?
An MSI installer, a CAB archive, and XCOPY command.
3. 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.
4. What namespaces are necessary to create a localized application?
System.Globalization and System.Resources.
5. What is the smallest unit of execution in .NET?
an Assembly.

Page 21 of 115
6. 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.
7. How do you convert a value-type to a reference-type?
Use Boxing.
8. 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.

8) What is a delegate?

1. A strongly typed function pointer.


2. A light weight thread or process that can call a single method.
3. A reference to an object in a different process.
4. An inter-process message channel.

9) How does assembly versioning in .NET prevent DLL Hell?

1. The runtime checks to see that only one version of an assembly


is on the machine at any one time.
2. .NET allows assemblies to specify the name AND the
version of any assemblies they need to run.
3. The compiler offers compile time checking for backward
compatibility.
4. It doesn.t.

10) Which .Gang of Four. design pattern is shown below?

public class A {

private A instance;

private A() {

Page 22 of 115
public
static A Instance {

get

if ( A == null )

A = new A();

return instance;

1. Factory
2. Abstract Factory
3. Singleton
4. Builder

11) In the NUnit test framework, which attribute must adorn a


test class in order for it to be picked up by the NUnit GUI?

1. TestAttribute
2. TestClassAttribute
3. TestFixtureAttribute
4. NUnitTestClassAttribute

12) Which of the following operations can you NOT perform on


an ADO.NET DataSet?

1. A DataSet can be synchronised with the database.


2. A DataSet can be synchronised with a RecordSet.
3. A DataSet can be converted to XML.
4. You can infer the schema from a DataSet.

13) In Object Oriented Programming, how would you describe


encapsulation?

1. The conversion of one type of object to another.


2. The runtime resolution of method calls.

Page 23 of 115
3. The exposition of data.
4. The separation of interface and implementation.

^Back to Top

.NET deployment questions

1. What do you know about .NET assemblies? Assemblies are


the smallest units of versioning and deployment in the .NET
application. Assemblies are also the building blocks for programs
such as Web services, Windows services, serviced components,
and .NET remoting applications.
2. What’s the difference between private and shared
assembly? Private assembly is used inside an application only
and does not have to be identified by a strong name. Shared
assembly can be used by multiple applications and has to have a
strong name.
3. What’s a strong name? A strong name includes the name of
the assembly, version number, culture identity, and a public key
token.
4. How can you tell the application to look for assemblies at
the locations other than its own install? Use the
directive in the XML .config file for a given application.

<probing privatePath=”c:\mylibs; bin\debug” />

should do the trick. Or you can add additional search paths in the
Properties box of the deployed application.

5. How can you debug failed assembly binds? Use the


Assembly Binding Log Viewer (fuslogvw.exe) to find out the
paths searched.
6. Where are shared assemblies stored? Global assembly
cache.
7. How can you create a strong name for a .NET
assembly? With the help of Strong Name tool (sn.exe).
8. Where’s global assembly cache located on the
system? Usually C:\winnt\assembly or C:\windows\assembly.
9. Can you have two files with the same file name in
GAC? Yes, remember that GAC is a very special folder, and while
normally you would not be able to place two files with the same
name into a Windows folder, GAC differentiates by version
number as well, so it’s possible for MyApp.dll and MyApp.dll to

Page 24 of 115
co-exist in GAC if the first one is version 1.0.0.0 and the second
one is 1.1.0.0.
10. So let’s say I have an application that uses MyApp.dll
assembly, version 1.0.0.0. There is a security bug in that
assembly, and I publish the patch, issuing it under name
MyApp.dll 1.1.0.0. How do I tell the client applications
that are already installed to start using this new
MyApp.dll? Use publisher policy. To configure a publisher policy,
use the publisher policy configuration file, which uses a format
similar app .config file. But unlike the app .config file, a publisher
policy file needs to be compiled into an assembly and placed in
the GAC.
11. What is delay signing? Delay signing allows you to place a
shared assembly in the GAC by signing the assembly with just
the public key. This allows the assembly to be signed with the
private key at a later stage, when the development process is
complete and the component or assembly is ready to be
deployed. This process enables developers to work with shared
assemblies as if they were strongly named, and it secures the
private key of the signature from being accessed at different
stages of development.
1. What is an AppDomain? What is a process? What is
thread? What is the difference between AppDomain and
process?
Process: A computer program is a set of instructions. Operating
system executes a computer program by allocating a process for
a program. Several processes may be associated with the
execution of a single program. A process is an instance of
machine code associated with a program. It has memory for
instructions, data, a call stack and a heap

AppDomain: An AppDomain is a light-weight process which


separates one application in .NET with another. CLR creates an
AppDomain when an application is loaded. Each application will
have an AppDomain associated. Each AppDomain can have
different threads running in it. Each app domain will have its
associated code, data and configuration. Hence when one
application crashes, it does not affect other.

Page 25 of 115
Thread: Each process can have multiple threads. Multiple
threads can share same execution code and resources. A multi-
threaded process can perform several tasks concurrently.

2. What is a runtime host?

.NET framework supports different type of applications like Web,


windows, console etc,. Each type of application needs a runtime
host to start it. This runtime host loads the runtime into a
process, creates the application with in the process and loads the
application code into the process.

Runtime hosts included in .NET framework are

ASP.NET: It loads the runtime that can handle a web request


into the process. ASP.NET also creates an application domain for
each Web application that will run on a Web server.

Microsoft Internet Explorer: It creates an application domain


to run managed controls.

Shell executables: When ever a runtime executable is


launched from the shell, this executable invokes the
corresponding runtime host.

3. What is the difference between manageable and


unmanageable code?

Code which targets the .NET framework CLR is manageable


meaning CLR can provide its services like type safety, memory
management, exceptional handling etc to this type of code.
Managed code is always compiled into MSIL. When a .NET

Page 26 of 115
application is run this compiled MSIL is compiled to native code
using JIT (Just In Time compiler). This JIT generates the native
code as per the hardware specification on the system. Since all
this process happens under the control of a managed
environment CLR, CLR provides all its rich functionality. Managed
code provides platform independence since the code is converted
to MSIL and then converted to native code depending on the
system architecture.

The code that does not target CLR is unmanageable. It cannot


run under CLR. This code directly runs under OS control.
Applications written in traditional applications like C++, VB, C
generate unmanaged code. This targets the computer
architecture. Unmanaged code is always compiled to target a
specific architecture and will only run on the intended platform.
This means that if you want to run the same code on different
architecture then you will have to recompile the code using that
particular architecture. Unmanaged code is always compiled
directly to the native code which is architecture specific. This
code cannot be executed on other platforms that are different
than the one on which the code was compiled. All the features
provided by CLR are unavailable and are to be taken care by the
code. Hence this causes memory leaks in traditional applications.

4. ExplainValue and reference types?

“System.Object” is the base class from all the .NET classes.

Value types: Value types inherit from


the System.ValueType class, which in turn, inherits
from System.Object. Value types are stored on stack. They are
implicitly sealed. Structs and Enumerations are value types and
they are always stored on stack. A value type cannot contain a
null value. Variables that are value types store data.

Page 27 of 115
Reference types: Variables to reference types referred to as
object, store reference to actual data. Actual data is stored on
the heap and reference is stored on the stack. This allows the
garbage collector to track outstanding references to a particular
instance and free the instance when no references

remain.

Integral
types : sbyte, byte, char, short, ushort, int, uint, long, ulong
Floating Point types: float, double
Decimal types: decimal

5. What is the role of garbage collector in .NET?

Objects created are stored on heap. Since the memory (here


heap) is exhaustible, .NET identifies a mechanism to collect the
unused memory(heap). GC does an automatic sweep of heap
once it is full. GC can only destroy managed objects.

GC will finalize all the objects in the memory that are not being
used anymore and thereby freeing the memory allocated to
them.

Page 28 of 115
.NET uses a three-generation approach to collecting memory.
Newly allocated memory tends to be freed more frequently than
older allocations, which tend to be more permanent. Gen 0
(Zero) is the youngest generation and, after a garbage
collection, any survivors go on to Gen 1. Likewise, any survivors
of a Gen 1 collection go on to Gen 2. Usually garbage collection
will occur only on Gen 0, and only if after it has reached some
limit. Until memory is exhausted, the cost of allocating each new
object is that of incrementing a pointer--which is close to the
performance of advancing the stack pointer.

CLR calls the GC when there is a high memory pressure and it is


not able to find any exact place to allocate a new object or the
applied threshold is reached.

6. Can you force Garbage collection if so how?

In applications with significant memory requirements, you can


force garbage collection by invoking the GC.Collect method from
the program.

7. What is CLR?

CLR is a runtime environment provided by .NET framework.


Developers write code in either C# or VB.NET.
.NET compilers convert this high level code into Microsoft
Intermediate Language(MSIL). At runtime JIT compiler converts
the MSIL into native code specific to the OS. CLR runs MSIL.
CLR provides memory management, exceptional handling,
security etc to the .NET code.

Page 29 of 115
8. Explain CLS and CTS?

CLS: Common Language specification is a set of rules that are to


be followed by a language in order to be .NET complaint. This
facilitates cross-language integration. Programs written in one
.NET language can interoperate with programs written in another
.NET language.

CTS: Common Type System Common Type System (CTS)


describes how types are declared, used and managed. CTS
facilitates cross-language integration, type safety, and high
performance code execution.

9. What is Type safety in .NET?


Type-safe code accesses only the memory locations it is
authorized to access. For example, type-safe code cannot read
values from another object's private fields. It accesses types
only in well-defined, allowable ways. If we want to work directly
with memory addresses and can manipulate bytes at these
addresses then we have to declare that code chunk
as unsafe using the unsafeKeyword in C#. So that CLR will not
do any extra verification on this code.

Actually during just-in-time (JIT) compilation, an optional


verification process examines the metadata and Microsoft
intermediate language (MSIL) of a method to be JIT-compiled
into native machine code to verify that they are type safe. This
process is skipped if the code has permission to bypass
verification. For example, the runtime cannot prevent
unmanaged code from calling into native (unmanaged) code and
performing malicious operations. When code is type safe, the
runtime's security enforcement mechanism ensures that it does
not access native code unless it has permission to do so. All code
that is not type safe must have been grantedSecurity
Permission with the passed enum member SkipVerification to
run.

Page 30 of 115
10. What is an assembly?
An assembly is a basic building block for an application. It can be
a DLL or EXE. An assembly contains IL. It consists of metadata
about the types inside the assembly.

194. In which Scenario you will go for Interface or Abstract 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.
Even though class inheritance allows your classes to inherit
implementation from a base class, it also forces you to make most of your
design decisions when the class is first published.
Abstract classes are useful when creating components because they allow
you specify an invariant level of functionality in some methods, but leave
the implementation of other methods until a specific implementation of that
class is needed. They also version well, because if additional functionality
is needed in derived classes, it can be added to the base class without
breaking code.

Interfaces vs. Abstract Classes


Feature Interface Abstract class
A class may
Multiple A class may extend only one
implement several
inheritance abstract class.
interfaces.
An abstract class can
An interface cannot
provide complete code,
Default provide any code at
default code, and/or just
implementation all, much less
stubs that have to be
default code.
overridden.
Static final constants
only, can use them
without qualification
in classes that
implement the
interface. On the
Both instance and static
other paw, these
constants are possible. Both
unqualified names
Constants static and instance intialiser
pollute the
code are also possible to
namespace. You
compute the constants.
can use them and it
is not obvious where
they are coming
from since the
qualification is
optional.

Page 31 of 115
An interface
implementation may A third party class must be
Third party
be added to any rewritten to extend only from
convenience
existing third party the abstract class.
class.
Interfaces are often
An abstract class defines the
used to describe the
core identity of its
peripheral abilities of
descendants. If you defined
a class, not its
a Dog abstract class then
central identity, e.g.
Damamation descendants
is-a vs -able or an Automobile class
are Dogs, they are not
can-do might implement the
merely dogable.
Recyclable
Implemented interfaces
interface, which
enumerate the general
could apply to many
things a class can do, not
otherwise totally
the things a class is.
unrelated objects.
Plug-in You can write a new You must use the abstract
replacement module class as-is for the code
for an interface that base, with all its attendant
contains not one baggage, good or bad. The
stick of code in abstract class author has
common with the imposed structure on you.
existing Depending on the
implementations. cleverness of the author of
When you the abstract class, this may
implement the be good or bad. Another
interface, you start issue that's important is what
from scratch without I call "heterogeneous vs.
any default homogeneous." If
implementation. You implementors/subclasses
have to obtain your are homogeneous, tend
tools from other towards an abstract base
classes; nothing class. If they are
comes with the heterogeneous, use an
interface other than interface. (Now all I have to
a few constants. do is come up with a good
This gives you definition of
freedom to hetero/homogeneous in this
implement a context.) If the various
radically different objects are all of-a-kind, and
internal design. share a common state and
behavior, then tend towards
a common base class. If all
they share is a set of method

Page 32 of 115
signatures, then tend
towards an interface.
If all the various If the various
implementations implementations are all of a
Homogeneity share is the method kind and share a common
signatures, then an status and behavior, usually
interface works best. an abstract class works best.
If your client code
Just like an interface, if your
talks only in terms of
client code talks only in
an interface, you
terms of an abstract class,
can easily change
Maintenance you can easily change the
the concrete
concrete implementation
implementation
behind it, using a factory
behind it, using a
method.
factory method.
Slow, requires extra
indirection to find the
corresponding
method in the actual
Speed Fast
class. Modern JVMs
are discovering
ways to reduce this
speed penalty.
The constant
declarations in an
You can put shared code
interface are all
into an abstract class, where
presumed public
you cannot into an interface.
static final, so you
If interfaces want to share
may leave that part
code, you will have to write
out. You can't call
other bubblegum to arrange
any methods to
Terseness that. You may use methods
compute the initial
to compute the initial values
values of your
of your constants and
constants. You need
variables, both instance and
not declare
static. You must declare all
individual methods
the individual methods of an
of an interface
abstract class abstract.
abstract. They are
all presumed so.
Adding If you add a new If you add a new method to
functionality method to an an abstract class, you have
interface, you must the option of providing a
track down all default implementation of it.
implementations of Then all existing code will
that interface in the continue to work without

Page 33 of 115
universe and
provide them with a
concrete change.
implementation of
that method.
196. see the code

197. interface ICommon


198. {
199. int getCommon();
200. }
201. interface ICommonImplements1:ICommon
202. {
203. }
204. interface ICommonImplements2:ICommon
205. {
206. }
207. public class a:ICommonImplements1,ICommonImplements2
208. {
}

How to implement getCommon method in class a? Are you seeing any


problem in the implementation?
Ans:

public class a:ICommonImplements1,ICommonImplements2


{
public int getCommon()
{
return 1;
}
}
209. interface IWeather
210. {
211. void display();
212. }
213. public class A:IWeather
214. {
215. public void display()
216. {
217. MessageBox.Show("A");
218. }
219. }
220. public class B:A
221. {
222. }

Page 34 of 115
223. public class C:B,IWeather
224. {
225. public void display()
226. {
227. MessageBox.Show("C");
228. }
229. }

230. When I instantiate C.display(), will it work?

231. interface IPrint


232. {
233. string Display();
234. }
235. interface IWrite
236. {
237. string Display();
238. }
239. class PrintDoc:IPrint,IWrite
240. {
241. //Here is implementation
242. }

how to implement the Display in the class printDoc (How to resolve the
naming Conflict) A: no naming conflicts

class PrintDoc:IPrint,IWrite
{
public string Display()
{
return "s";
}
}
243. interface IList
244. {
245. int Count { get; set; }
246. }
247. interface ICounter
248. {
249. void Count(int i);
250. }
251. interface IListCounter: IList, ICounter {}
252. class C
253. {
254. void Test(IListCounter x)
255. {

Page 35 of 115
256. x.Count(1); // Error
257. x.Count = 1; // Error
258. ((IList)x).Count = 1; // Ok, invokes IList.Count.set
259. ((ICounter)x).Count(1); // Ok, invokes ICounter.Count
260. }
261. }

316. Which method do you invoke on the DataAdapter control to


load your generated dataset with data?
Fill()
317. Explain different methods and Properties of DataReader which
you have used in your project?
Read
GetString
GetInt32
while (myReader.Read())
Console.WriteLine("\t{0}\t{1}", myReader.GetInt32(0),
myReader.GetString(1));
myReader.Close();
318. What happens when we issue Dataset.ReadXml command?
Reads XML schema and data into the DataSet.
319. In how many ways we can retrieve table records count? How
to find the count of records in a dataset?
foreach(DataTable thisTable in myDataSet.Tables){
// For each row, print the values of each column.
foreach(DataRow myRow in thisTable.Rows){
320. How to check if a datareader is closed or opened?
IsClosed()

What is method to get XML and schema from Dataset?


ans: getXML () and get Schema ()

Differences between dataset.clone and dataset.copy?


Clone - Copies the structure of the DataSet, including all DataTable schemas,
relations, and constraints. Does not copy any data.
Copy - Copies both the structure and data for this DataSet.

1.Does C# support multiple-inheritance?


No. But you can use Interfaces.

2.Where is a protected class-level variable available?


It is available to any sub-class derived from base class

3.Are private class-level variables inherited?


Yes, but they are not accessible.

Page 36 of 115
4.Describe the accessibility modifier “protected internal”.
It is available to classes that are within the same assembly and derived
from the specified base class.

6.Which class is at the top of .NET class hierarchy?


System.Object.

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

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

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

10.Can you store multiple data types in System.Array?


No.

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

12.How can you sort the elements of the array in descending order?
By calling Sort() and then Reverse() methods.

13.What’s the .NET collection class that allows an element to be

Page 37 of 115
accessed using a unique key?
HashTable.

14.What class is underneath the SortedList class?


A sorted HashTable.

15.Will the finally block get executed if an exception has not occurred?
Yes.

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

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

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

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

2.Can you prevent your class from being inherited by another class?
Yes. The keyword “sealed” will prevent the class from being inherited.

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

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

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

Page 38 of 115
base abstract methods have been overridden.

2. When at least one of the methods in the class is abstract.

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

7.Why can’t you specify the accessibility modifier for methods inside
the interface?
They all must be public, and are therefore public by default.

8.Can you inherit multiple interfaces?


Yes. .NET does support multiple interfaces.

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

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

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

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

Page 39 of 115
2. What does the keyword “virtual” declare for a method or property?
The method or property can be overridden.

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

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

5. What are the different ways a method can be overloaded?


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

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

1. What’s a delegate?
A delegate object encapsulates a reference to a method.

2. What’s a multicast delegate?


A delegate that has multiple handlers assigned to it. Each assigned
handler (method) is called.

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

4. How do you inherit from a class in C#?


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

5. Does C# support multiple inheritance?


No, use interfaces instead.

Page 40 of 115
6. When you inherit a protected class-level variable, who is it available
to?
Classes in the same namespace.

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

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

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

10. What’s the top .NET class that everything is derived from?
System.Object.

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

12. What does the keyword virtual mean in the method definition?
The method can be over-ridden.

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

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

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

Page 41 of 115
16. 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.

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

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

19. What’s an interface class?


It’s an abstract class with public abstract methods all of which must be
implemented in the inherited classes.

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

21. Can you inherit multiple interfaces?


Yes, why not.

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

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

24. How can you overload a method?


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

Page 42 of 115
25. 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.

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

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

What is a partial class. Give an example?


A partial class is a class whose definition is present in 2 or more files. Each
source file contains a section of the class, and all parts are combined when
the application is compiled. To split a class definition, use the partial keyword
as shown in the example below. Student class is split into 2 parts. The first part
defines the study() method and the second part defines the Play() method.
When we compile this program both the parts will be combined and compiled.
Note that both the parts uses partial keyword and public access modifier.

using System;
namespace PartialClass
{
public partial class Student
{
public void Study()
{
Console.WriteLine("I am studying");
}
}
public partial class Student
{
public void Play()
{
Console.WriteLine("I am Playing");
}

Page 43 of 115
}
public class Demo
{
public static void Main()
{
Student StudentObject = new Student();
StudentObject.Study();
StudentObject.Play();
}
}
}

It is very important to keep the following points in mind when creating


partial classes.
1. All the parts must use the partial keyword.
2. All the parts must be available at compile time to form the final class.
3. All the parts must have the same access modifiers - public, private,
protected etc.
4. Any class members declared in a partial definition are available to all the
other parts.
5. The final class is the combination of all the parts at compile time.

What are the advantages of using partial classes?


1. When working on large projects, spreading a class over separate files
enables multiple programmers to work on it at the same time.

2. When working with automatically generated source, code can be added to


the class without having to recreate the source file. Visual Studio uses this
approach when it creates Windows Forms, Web service wrapper code, and so
on. You can create code that uses these classes without having to modify the
file created by Visual Studio.

Is it possible to create partial structs, interfaces and methods?


Yes, it is possible to create partial structs, interfaces and methods. We can
create partial structs, interfaces and methods the same way as we create
partial classes.

Will the following code compile?


using System;
namespace PartialClass
{
public partial class Student
{
public void Study()
{
Console.WriteLine("I am studying");

Page 44 of 115
}
}
public abstract partial class Student
{
public void Play()
{
Console.WriteLine("I am Playing");
}
}
public class Demo
{
public static void Main()
{
Student StudentObject = new Student();
}
}
}

No, a compile time error will be generated stating "Cannot create an instance
of the abstract class or interface "PartialClass.Student". This is because, if any
part is declared abstract, then the whole class becomes abstract. Similarly if
any part is declared sealed, then the whole class becomes sealed and if any
part declares a base class, then the whole class inherits that base class.

Can you create partial delegates and enumerations?


No, you cannot create partial delegates and enumerations.

Can different parts of a partial class inherit from different interfaces?


Yes, different parts of a partial class can inherit from different interfaces.

Can you specify nested classes as partial classes?


Yes, nested classes can be specified as partial classes even if the containing
class is not partial. An example is shown below.

class ContainerClass
{
public partial class Nested
{
void Test1() { }
}
public partial class Nested
{
void Test2() { }
}
}

Page 45 of 115
How do you create partial methods?
To create a partial method we create the declaration of the method in one
part of the partial class and implementation in the other part of the partial
class. The implementation is optional. If the implementation is not provided,
then the method and all the calls to the method are removed at compile time.
Therefore, any code in the partial class can freely use a partial method, even if
the implementation is not supplied. No compile-time or run-time errors will
result if the method is called but not implemented. In summary a partial
method declaration consists of two parts. The definition, and the
implementation. These may be in separate parts of a partial class, or in the
same part. If there is no implementation declaration, then the compiler
optimizes away both the defining declaration and all calls to the method.

The following are the points to keep in mind when creating partial methods.
1. Partial method declarations must begin partial keyword.
2. The return type of a partial method must be void.
3. Partial methods can have ref but not out parameters.
4. Partial methods are implicitly private, and therefore they cannot be virtual.
5. Partial methods cannot be extern, because the presence of the body
determines whether they are defining or implementing.

What is the use of partial methods?


Partial methods can be used to customize generated code. They allow for a
method name and signature to be reserved, so that generated code can call the
method but the developer can decide whether to implement the method. Much
like partial classes, partial methods enable code created by a code generator
and code created by a human developer to work together without run-time
costs.
What is a nested type. Give an example?
A type(class or a struct) defined inside another class or struct is called a nested
type. An example is shown below. InnerClass is inside ContainerClass, Hence
InnerClass is called as nested class.

using System;
namespace Nested
{
class ContainerClass
{
class InnerClass
{
public string str = "A string variable in nested class";
}

public static void Main()


{
InnerClass nestedClassObj = new InnerClass();

Page 46 of 115
Console.WriteLine(nestedClassObj.str);
}
}
}

Will the following code compile?


using System;
namespace Nested
{
class ContainerClass
{
class InnerClass
{
public string str = "A string variable in nested class";
}
}

class Demo
{
public static void Main()
{
InnerClass nestedClassObj = new InnerClass();
Console.WriteLine(nestedClassObj.str);
}
}
}

No, the above code will generate a compile time error stating - The type or
namespace name 'InnerClass' could not be found (are you missing a using
directive or an assembly reference?). This is bcos InnerClass is inside
ContainerClass and does not have any access modifier. Hence inner class is like
a private member inside ContainerClass. For the above code to compile and
run, we should make InnerClass public and use the fully qualified name when
creating the instance of the nested class as shown below.

using System;
namespace Nested
{
class ContainerClass
{
public class InnerClass
{
public string str = "A string variable in nested class";
}
}

Page 47 of 115
class Demo
{
public static void Main()
{
ContainerClass.InnerClass nestedClassObj = new
ContainerClass.InnerClass();
Console.WriteLine(nestedClassObj.str);
}
}
}

Can the nested class access, the Containing class. Give an example?
Yes, the nested class, or inner class can access the containing or outer class as
shown in the example below. Nested types can access private and protected
members of the containing type, including any inherited private or protected
members.

using System;
namespace Nested
{
class ContainerClass
{
string OuterClassVariable = "I am an outer class variable";

public class InnerClass


{
ContainerClass ContainerClassObject = new ContainerClass();
string InnerClassVariable = "I am an Inner class variable";
public InnerClass()
{
Console.WriteLine(ContainerClassObject.OuterClassVariable);
Console.WriteLine(this.InnerClassVariable);
}
}
}

class Demo
{
public static void Main()
{
ContainerClass.InnerClass nestedClassObj = new
ContainerClass.InnerClass();
}
}
}

Page 48 of 115
What is the ouput of the following program?
using System;
namespace Nested
{
class ContainerClass
{
public ContainerClass()
{
Console.WriteLine("I am a container class");
}

public class InnerClass : ContainerClass


{
public InnerClass()
{
Console.WriteLine("I am an inner class");
}
}
}

class DemoClass : ContainerClass.InnerClass


{
public DemoClass()
{
Console.WriteLine("I am a Demo class");
}
public static void Main()
{
DemoClass DC = new DemoClass();
}
}
}

Output:
I am a container class
I am an inner class
I am a Demo class

The above program has used the concepts of inheritance and nested classes.
The ContainerClass is at the top in the inheritance chain. The nested InnerClass
derives from outer ContainerClass. Finally the DemoClass derives from nested
InnerClass. As all the 3 classes are related by inheritance we have the above
output.

What is a Destructor?
A Destructor has the same name as the class with a tilde character and is used

Page 49 of 115
to destroy an instance of a class.

Can a class have more than 1 destructor?


No, a class can have only 1 destructor.

Can structs in C# have destructors?


No, structs can have constructors but not destructors, only classes can have
destructors.

Can you pass parameters to destructors?


No, you cannot pass parameters to destructors. Hence, you cannot overload
destructors.

Can you explicitly call a destructor?


No, you cannot explicitly call a destructor. Destructors are invoked automatically
by the garbage collector.

Why is it not a good idea to use Empty destructors?


When a class contains a destructor, an entry is created in the Finalize queue.
When the destructor is called, the garbage collector is invoked to process the
queue. If the destructor is empty, this just causes a needless loss of
performance.

Is it possible to force garbage collector to run?


Yes, it possible to force garbage collector to run by calling the Collect() method,
but this is not considered a good practice because this might create a
performance over head. Usually the programmer has no control over when the
garbage collector runs. The garbage collector checks for objects that are no
longer being used by the application. If it considers an object eligible for
destruction, it calls the destructor(if there is one) and reclaims the memory used
to store the object.

Usually in .NET, the CLR takes care of memory management. Is there any
need for a programmer to explicitly release memory and resources? If yes,
why and how?
If the application is using expensive external resource, it is recommend to
explicitly release the resource before the garbage collector runs and frees the
object. We can do this by implementing the Dispose method from the
IDisposable interface that performs the necessary cleanup for the object. This
can considerably improve the performance of the application.

What is a constructor in C#?


Constructor is a class method that is executed when an object of a class is
created. Constructor has the same name as the class, and usually used to
initialize the data members of the new object.

Page 50 of 115
In C#, What will happen if you do not explicitly provide a constructor for a
class?
If you do not provide a constructor explicitly for your class, C# will create one
by default that instantiates the object and sets all the member variables to
their default values.

Structs are not reference types. Can structs have constructors?


Yes, even though Structs are not reference types, structs can have
constructors.

We cannot create instances of static classes. Can we have constructors for


static classes?
Yes, static classes can also have constructors.

Can you prevent a class from being instantiated?


Yes, a class can be prevented from being instantiated by using a private
constructor as shown in the example below.

using System;
namespace TestConsole
{
class Program
{
public static void Main()
{
//Error cannot create instance of a class with private constructor
SampleClass SC = new SampleClass();
}
}
class SampleClass
{
double PI = 3.141;
private SampleClass()
{
}
}
}

Can a class or a struct have multiple constructors?


Yes, a class or a struct can have multiple constructors. Constructors in csharp
can be overloaded.

Can a child class call the constructor of a base class?


Yes, a child class can call the constructor of a base class by using the base
keyword as shown in the example below.

Page 51 of 115
using System;
namespace TestConsole
{
class BaseClass
{
public BaseClass(string str)
{
Console.WriteLine(str);
}
}

class ChildClass : BaseClass


{
public ChildClass(string str): base(str)
{
}

public static void Main()


{
ChildClass CC = new ChildClass("Calling base class constructor from child
class");
}
}
}

If a child class instance is created, which class constructor is called first -


base class or child class?
When an instance of a child class is created, the base class constructor is called
before the child class constructor. An example is shown below.

using System;
namespace TestConsole
{
class BaseClass
{
public BaseClass()
{
Console.WriteLine("I am a base class constructor");
}
}
class ChildClass : BaseClass
{
public ChildClass()
{
Console.WriteLine("I am a child class constructor");
}

Page 52 of 115
public static void Main()
{
ChildClass CC = new ChildClass();
}
}
}

Will the following code compile?


using System;
namespace TestConsole
{
class BaseClass
{
public BaseClass(string str)
{
Console.WriteLine(str);
}
}
class ChildClass : BaseClass
{
public ChildClass()
{
Console.WriteLine("I am a child class constructor");
}
public static void Main()
{
ChildClass CC = new ChildClass();
}
}
}

No, the above code will not compile. This is because, if a base class does not
offer a default constructor, the derived class must make an explicit call to a
base class constructor by using the base keyword as shown in the example
below.

using System;
namespace TestConsole
{
class BaseClass
{
public BaseClass(string str)
{
Console.WriteLine(str);
}
}

Page 53 of 115
class ChildClass : BaseClass
{
//Call the base class contructor from child class
public ChildClass() : base("A call to base class constructor")
{
Console.WriteLine("I am a child class constructor");
}
public static void Main()
{
ChildClass CC = new ChildClass();
}
}
}

Can a class have static constructor?


Yes, a class can have static constructor. Static constructors are called
automatically, immediately before any static fields are accessed, and are
generally used to initialize static class members. It is called automatically
before the first instance is created or any static members are referenced.
Static constructors are called before instance constructors. An example is
shown below.

using System;
namespace TestConsole
{
class Program
{
static int I;
static Program()
{
I = 100;
Console.WriteLine("Static Constructor called");
}
public Program()
{
Console.WriteLine("Instance Constructor called");
}
public static void Main()
{
Program P = new Program();
}
}
}

Can you mark static constructor with access modifiers?


No, we cannot use access modifiers on static constructor.

Page 54 of 115
Can you have parameters for static constructors?
No, static constructors cannot have parameters.

What happens if a static constructor throws an exception?


If a static constructor throws an exception, the runtime will not invoke it a
second time, and the type will remain uninitialized for the lifetime of the
application domain in which your program is running.

Give 2 scenarios where static constructors can be used?


1. A typical use of static constructors is when the class is using a log file and
the constructor is used to write entries to this file.
2. Static constructors are also useful when creating wrapper classes for
unmanaged code, when the constructor can call the LoadLibrary method.

Does C# provide copy constructor?


No, C# does not provide copy constructor.

Is the following code legal?


using System;
namespace Demo
{
class Program
{
public static void Main()
{

}
public void Sum(int FirstNumber, int SecondNumber)
{
int Result = FirstNumber + SecondNumber;
}

public int Sum(int FirstNumber, int SecondNumber)


{
int Result = FirstNumber + SecondNumber;
}
}
}

No, The above code does not compile. You cannot overload a method based on
the return type. To overload a method in C# either the number or type of
parameters should be different. In general the return type of a method is not
part of the signature of the method for the purposes of method overloading.
However, it is part of the signature of the method when determining the
compatibility between a delegate and the method that it points to.

Page 55 of 115
What is the difference between method parameters and method arguments.
Give an example?
In the example below FirstNumber and SecondNumber are method parameters
where as FN and LN are method arguments. The method definition specifies the
names and types of any parameters that are required. When calling code calls
the method, it provides concrete values called arguments for each parameter.
The arguments must be compatible with the parameter type but the argument
name (if any) used in the calling code does not have to be the same as the
parameter named defined in the method.

using System;
namespace Demo
{
class Program
{
public static void Main()
{
int FN = 10;
int SN = 20;
//FN and LN are method arguments
int Total = Sum(FN, SN);
Console.WriteLine(Total);
}
//FirstNumber and SecondNumber are method parameters
public static int Sum(int FirstNumber, int SecondNumber)
{
int Result = FirstNumber + SecondNumber;
return Result;
}
}
}

Explain the difference between passing parameters by value and passing


parameters by reference with an example?
We can pass parameters to a method by value or by reference. By default all
value types are passed by value where as all reference types are passed by
reference. By default, when a value type is passed to a method, a copy is
passed instead of the object itself. Therefore, changes to the argument have
no effect on the original copy in the calling method.An example is shown
below.

using System;
namespace Demo
{
class Program

Page 56 of 115
{
public static void Main()
{
int I = 10;
int K = Function(I);

Console.WriteLine("I = " + I);


Console.WriteLine("K = " + K);
}
public static int Function(int Number)
{
int ChangedValue = Number + 1;
return ChangedValue;
}
}
}

By default, reference types are passed by reference. When an object of a


reference type is passed to a method, the reference points to the original
object, not a copy of the object. Changes made through this reference will
therefore be reflected in the calling method. Reference types are created by
using the class keyword as shown in the example below.

using System;
namespace Demo
{
class Program
{
public static void Main()
{
ReferenceTypeExample Object = new ReferenceTypeExample();
Object.Number = 20;
Console.WriteLine("Original Object Value = " + Object.Number);
Function(Object);
Console.WriteLine("Object Value after passed to the method= " +
Object.Number);
}
public static void Function(ReferenceTypeExample ReferenceTypeObject)
{
ReferenceTypeObject.Number = ReferenceTypeObject.Number + 5;
}
}

class ReferenceTypeExample
{
public int Number;

Page 57 of 115
}
}

Can you pass value types by reference to a method?


Yes, we can pass value types by by reference to a method. An example is
shown below.

using System;
namespace Demo
{
class Program
{
public static void Main()
{
int I = 10;
Console.WriteLine("Value of I before passing to the method = " + I);
Function(ref I);
Console.WriteLine("Value of I after passing to the method by reference= " +
I);
}
public static void Function(ref int Number)
{
Number = Number + 5;
}
}
}

If a method's return type is void, can you use a return keyword in the
method?
Yes, Even though a method's return type is void, you can use the return
keyword to stop the execution of the method as shown in the example below.
using System;
namespace Demo
{
class Program
{
public static void Main()
{
SayHi();
}
public static void SayHi()
{
Console.WriteLine("Hi");
return;
Console.WriteLine("This statement will never be executed");
}

Page 58 of 115
}
}

What are Properties in C#. Explain with an example?


Properties in C# are class members that provide a flexible mechanism to read,
write, or compute the values of private fields. Properties can be used as if they
are public data members, but they are actually special methods called accessors.
This enables data to be accessed easily and still helps promote the safety and
flexibility of methods.

In the example below _firstName and _lastName are private string variables
which are accessible only inside the Customer class. _firstName and _lastName
are exposed using FirstName and LastName public properties respectively. The
get property accessor is used to return the property value, and a set accessor is
used to assign a new value. These accessors can have different access levels.
The value keyword is used to define the value being assigned by the set
accessor. The FullName property computes the full name of the customer. Full
Name property is readonly, because it has only the get accessor. Properties that
do not implement a set accessor are read only.

The code block for the get accessor is executed when the property is read and
the code block for the set accessor is executed when the property is assigned a
new value.

using System;
class Customer
{
// Private fileds not accessible outside the class.
private string _firstName = string.Empty;
private string _lastName = string.Empty;
private string _coutry = string.Empty;

// public FirstName property exposes _firstName variable


public string FirstName
{
get
{
return _firstName;
}
set
{
_firstName = value;
}
}
// public LastName property exposes _lastName variable

Page 59 of 115
public string LastName
{
get
{
return _lastName;
}
set
{
_lastName = value;
}
}
// FullName property is readonly and computes customer full name.
public string FullName
{
get
{
return _lastName + ", " + _firstName;
}
}
//Country Property is Write Only
public string Country
{
set
{
_coutry = value;
}
}

}
class MainClass
{
public static void Main()
{
Customer CustomerObject = new Customer();
//This line will call the set accessor of FirstName Property
CustomerObject.FirstName = "David";
//This line will call the set accessor of LastName Property
CustomerObject.LastName = "Boon";
//This line will call the get accessor of FullName Property
Console.WriteLine("Customer Full Name is : " + CustomerObject.FullName);
}
}

Explain the 3 types of properties in C# with an example?


1. Read Only Properties: Properties without a set accessor are considered read-
only. In the above example FullName is read only property.

Page 60 of 115
2. Write Only Properties: Properties without a get accessor are considered write-
only. In the above example Country is write only property.
3. Read Write Properties: Properties with both a get and set accessor are
considered read-write properties. In the above example FirstName and
LastName are read write properties.

What are the advantages of properties in C#?


1. Properties can validate data before allowing a change.
2. Properties can transparently expose data on a class where that data is actually
retrieved from some other source such as a database.
3. Properties can take an action when data is changed, such as raising an event
or changing the value of other fields.

What is a static property. Give an example?


A property that is marked with a static keyword is considered as static property.
This makes the property available to callers at any time, even if no instance of
the class exists. In the example below PI is a static property.

using System;
class Circle
{
private static double _pi = 3.14;
public static double PI
{
get
{
return _pi;
}
}
}
class MainClass
{
public static void Main()
{
Console.WriteLine(Circle.PI);
}
}

What is a virtual property. Give an example?


A property that is marked with virtual keyword is considered virtual property.
Virtual properties enable derived classes to override the property behavior by
using the override keyword. In the example below FullName is virtual property in
the Customer class. BankCustomer class inherits from Customer class and
overrides the FullName virtual property. In the output you can see the over riden
implementation. A property overriding a virtual property can also be sealed,
specifying that for derived classes it is no longer virtual.

Page 61 of 115
using System;
class Customer
{
private string _firstName = string.Empty;
private string _lastName = string.Empty;

public string FirstName


{
get
{
return _firstName;
}
set
{
_firstName = value;
}
}
public string LastName
{
get
{
return _lastName;
}
set
{
_lastName = value;
}
}
// FullName is virtual
public virtual string FullName
{
get
{
return _lastName + ", " + _firstName;
}
}
}
class BankCustomer : Customer
{
// Overiding the FullName virtual property derived from customer class
public override string FullName
{
get
{

Page 62 of 115
return "Mr. " + FirstName + " " + LastName;
}
}
}
class MainClass
{
public static void Main()
{
BankCustomer BankCustomerObject = new BankCustomer();
BankCustomerObject.FirstName = "David";
BankCustomerObject.LastName = "Boon";
Console.WriteLine("Customer Full Name is : " +
BankCustomerObject.FullName);
}
}

What is an abstract property. Give an example?


A property that is marked with abstract keyword is considered abstract property.
An abstract property should not have any implementation in the class. The
derived classes must write their own implementation. In the example below
FullName property is abstract in the Customer class. BankCustomer class
overrides the inherited abstract FullName property with its own implementation.

using System;
abstract class Customer
{
private string _firstName = string.Empty;
private string _lastName = string.Empty;

public string FirstName


{
get
{
return _firstName;
}
set
{
_firstName = value;
}
}
public string LastName
{
get
{
return _lastName;

Page 63 of 115
}
set
{
_lastName = value;
}
}
// FullName is abstract
public abstract string FullName
{
get;
}
}
class BankCustomer : Customer
{
// Overiding the FullName abstract property derived from customer class
public override string FullName
{
get
{
return "Mr. " + FirstName + " " + LastName;
}
}
}
class MainClass
{
public static void Main()
{
BankCustomer BankCustomerObject = new BankCustomer();
BankCustomerObject.FirstName = "David";
BankCustomerObject.LastName = "Boon";
Console.WriteLine("Customer Full Name is : " +
BankCustomerObject.FullName);
}
}

Can you use virtual, override or abstract keywords on an accessor of a


static property?
No, it is a compile time error to use a virtual, abstract or override keywords on an
accessor of a static property.

What are constants in C#?


Constants in C# are immutable values which are known at compile time and do
not change for the life of the program. Constants are declared using the const
keyword. Constants must be initialized as they are declared. You cannot assign a
value to a constant after it isdeclared. An example is shown below.

Page 64 of 115
using System;
class Circle
{
public const double PI = 3.14;
public Circle()
{
//Error : You can only assign a value to a constant field at the time of
declaration
//PI = 3.15;
}
}
class MainClass
{
public static void Main()
{
Console.WriteLine(Circle.PI);
}
}

Can you declare a class or a struct as constant?


No, User-defined types including classes, structs, and arrays, cannot be const.
Only the C# built-in types excluding System.Object may be declared as const.
Use the readonly modifier to create a class, struct, or array that is initialized one
time at runtime (for example in a constructor) and thereafter cannot be changed.

Does C# support const methods, properties, or events?


No, C# does not support const methods, properties, or events.

Can you change the value of a constant filed after its declaration?
No, you cannot change the value of a constant filed after its declaration. In the
example below, the constant field PI is always 3.14, and it cannot be changed
even by the class itself. In fact, when the compiler encounters a constant
identifier in C# source code (for example, PI), it substitutes the literal value
directly into the intermediate language (IL) code that it produces. Because there
is no variable address associated with a constant at run time, const fields cannot
be passed by reference.

using System;
class Circle
{
public const double PI = 3.14;
}

How do you access a constant field declared in a class?


Constants are accessed as if they were static fields because the value of the
constant is the same for all instances of the type. You do not use the static

Page 65 of 115
keyword to declare them. Expressions that are not in the class that defines the
constant must use the class name, a period, and the name of the constant to
access the constant. In the example below constant field PI can be accessed in
the Main method using the class name and not the instance of the class. Trying
to access a constant field using a class instance will generate a compile time
error.

using System;
class Circle
{
public const double PI = 3.14;
}
class MainClass
{
public static void Main()
{
Console.WriteLine(Circle.PI);
Circle C = new Circle();
// Error : PI cannot be accessed using an instance
// Console.WriteLine(C.PI);
}
}

What are Access Modifiers in C#?


In C# there are 5 different types of Access Modifiers.
Public
The public type or member can be accessed by any other code in the same
assembly or another assembly that references it.

Private
The type or member can only be accessed by code in the same class or struct.

Protected
The type or member can only be accessed by code in the same class or struct,
or in a derived class.

Internal
The type or member can be accessed by any code in the same assembly, but
not from another assembly.

Protected Internal
The type or member can be accessed by any code in the same assembly, or by
any derived class in another assembly.

What are Access Modifiers used for?


Access Modifiers are used to control the accessibilty of types and members with

Page 66 of 115
in the types.

Can you use all access modifiers for all types?


No, Not all access modifiers can be used by all types or members in all contexts,
and in some cases the accessibility of a type member is constrained by the
accessibility of its containing type.

Can derived classes have greater accessibility than their base types?
No, Derived classes cannot have greater accessibility than their base types. For
example the following code is illegal.
using System;
internal class InternalBaseClass
{
public void Print()
{
Console.WriteLine("I am a Base Class Method");
}
}
public class PublicDerivedClass : InternalBaseClass
{
public static void Main()
{
Console.WriteLine("I am a Public Derived Class Method");
}
}

When you compile the above code an error will be generated stating
"Inconsistent accessibility: base class InternalBaseClass is less accessible than
class PublicDerivedClass".To make this simple, you cannot have a public class B
that derives from an internal class A. If this were allowed, it would have the effect
of making A public, because all protected or internal members of A are
accessible from the derived class.

Is the following code legal?

using System;
private class Test
{
public static void Main()
{
}
}

No, a compile time error will be generated stating "Namespace elements


cannot be explicitly declared as private, protected, or protected internal"

Page 67 of 115
Can you declare struct members as protected?
No, struct members cannot be declared protected. This is because structs do not
support inheritance.

Can the accessibility of a type member be greater than the accessibility of


its containing type?
No, the accessibility of a type member can never be greater than the accessibility
of its containing type. For example, a public method declared in an internal class
has only internal accessibility.

Can destructors have access modifiers?


No, destructors cannot have access modifiers.

What does protected internal access modifier mean?


The protected internal access means protected OR internal, not protected AND
internal. In simple terms, a protected internal member is accessible from any
class in the same assembly, including derived classes. To limit accessibility to
only derived classes in the same assembly, declare the class itself internal, and
declare its members as protected.

What is the default access modifier for a class,struct and an interface


declared directly with a namespace?
internal

Will the following code compile?

using System;
interface IExampleInterface
{
public void Save();
}

No, you cannot specify access modifer for an interface member. Interface
members are always public.

Can you specify an access modifier for an enumeration?


Enumeration members are always public, and no access modifiers can be
specified.

Why should you override the ToString() method?


All types in .Net inherit from system.object directly or indirectly. Because of this
inheritance, every type in .Net inherit the ToString() method from System.Object
class. Consider the example below.

using System;

Page 68 of 115
public class MainClass
{
public static void Main()
{
int Number = 10;
Console.WriteLine(Number.ToString());
}
}

In the above example Number.ToString() method will correctly give the string
representaion of int 10, when you call the ToString() method.

If you have a Customer class as shown in the below example and when you call
the ToString() method the output doesnot make any sense. Hence you have to
override the ToString() method, that is inherited from the System.Object class.

using System;
public class Customer
{
public string FirstName;
public string LastName;
}
public class MainClass
{
public static void Main()
{
Customer C = new Customer();
C.FirstName = "David";
C.LastName = "Boon";
Console.WriteLine(C.ToString());
}
}

The code sample below shows how to override the ToString() method in a class,
that would give the output you want.

using System;
public class Customer
{
public string FirstName;
public string LastName;

public override string ToString()


{
return LastName + ", " + FirstName;

Page 69 of 115
}
}
public class MainClass
{
public static void Main()
{
Customer C = new Customer();
C.FirstName = "David";
C.LastName = "Boon";
Console.WriteLine(C.ToString());
}
}

Explain polymorphism in C# with a simple example?


Polymorphism allows you to invoke derived class methods through a base class
reference during run-time. An example is shown below.
using System;
public class DrawingObject
{
public virtual void Draw()
{
Console.WriteLine("I am a drawing object.");
}
}
public class Triangle : DrawingObject
{
public override void Draw()
{
Console.WriteLine("I am a Triangle.");
}
}
public class Circle : DrawingObject
{
public override void Draw()
{
Console.WriteLine("I am a Circle.");
}
}
public class Rectangle : DrawingObject
{
public override void Draw()
{
Console.WriteLine("I am a Rectangle.");
}
}
public class DrawDemo

Page 70 of 115
{
public static void Main()
{
DrawingObject[] DrawObj = new DrawingObject[4];

DrawObj[0] = new Triangle();


DrawObj[1] = new Circle();
DrawObj[2] = new Rectangle();
DrawObj[3] = new DrawingObject();

foreach (DrawingObject drawObj in DrawObj)


{
drawObj.Draw();
}
}
}

When can a derived class override a base class member?


A derived class can override a base class member only if the base class member
is declared as virtual or abstract.

What is the difference between a virtual method and an abstract method?


A virtual method must have a body where as an abstract method should not have
a body.

Can fields inside a class be virtual?


No, Fields inside a class cannot be virtua. Only methods, properties, events and
indexers can be virtual.

Give an example to show for hiding base class methods?


Use the new keyword to hide a base class method in the derived class as shown
in the example below.
using System;
public class BaseClass
{
public virtual void Method()
{
Console.WriteLine("I am a base class method.");
}
}
public class DerivedClass : BaseClass
{
public new void Method()
{
Console.WriteLine("I am a child class method.");
}

Page 71 of 115
public static void Main()
{
DerivedClass DC = new DerivedClass();
DC.Method();
}
}

Can you access a hidden base class method in the derived class?
Yes, Hidden base class methods can be accessed from the derived class by
casting the instance of the derived class to an instance of the base class as
shown in the example below.
using System;
public class BaseClass
{
public virtual void Method()
{
Console.WriteLine("I am a base class method.");
}
}
public class DerivedClass : BaseClass
{
public new void Method()
{
Console.WriteLine("I am a child class method.");
}

public static void Main()


{
DerivedClass DC = new DerivedClass();
((BaseClass)DC).Method();
}
}

What is an abstract class?


An abstract class is an incomplete class and must be implemented in a derived
class.

Can you create an instance of an abstract class?


No, abstract classes are incomplete and you cannot create an instance of an
abstract class.

What is a sealed class?


A sealed class is a class that cannot be inherited from. This means, If you have a
class called Customer that is marked as sealed. No other class can inherit from
Customer class. For example, the below code generates a compile time error

Page 72 of 115
"MainClass cannot derive from sealed type Customer.
using System;
public sealed class Customer
{
}
public class MainClass : Customer
{
public static void Main()
{
}
}

What are abstract methods?


Abstract methods are methods that only the declaration of the method and no
implementation.

Will the following code compile?


using System;
public abstract class Customer
{
public abstract void Test()
{
Console.WriteLine("I am customer");
}
}
public class MainClass
{
public static void Main()
{
}
}
No, abstract methods cannot have body. Hence, the above code will generate a
compile time error stating "Customer.Test() cannot declare a body because it is
marked abstract"

Is the following code legal?


using System;
public class Customer
{
public abstract void Test();
}
public class MainClass
{
public static void Main()
{
}

Page 73 of 115
}

No, if a class has even a single abstract member, the class has to be marked
abstract. Hence the above code will generate a compile time error stating
"Customer.Test() is abstract but it is contained in nonabstract class Customer"

How can you force derived classes to provide new method


implementations for virtual methods?
Abstract classes can be used to force derived classes to provide new method
implementations for virtual methods. An example is shown below.
public class BaseClass
{
public virtual void Method()
{
// Original Implementation.
}
}

public abstract class AbstractClass : BaseClass


{
public abstract override void Method();
}

public class NonAbstractChildClass : AbstractClass


{
public override void Method()
{
// New implementation.
}
}

When an abstract class inherits a virtual method from a base class, the abstract
class can override the virtual method with an abstract method. If a virtual method
is declared abstract, it is still virtual to any class inheriting from the abstract class.
A class inheriting an abstract method cannot access the original implementation
of the method. In the above example, Method() on class NonAbstractChildClass
cannot call Method() on class BaseClass. In this way, an abstract class can force
derived classes to provide new method implementations for virtual methods.

Can a sealed class be used as a base class?


No, sealed class cannot be used as a base class. A compile time error will be
generated.

Will the following code compile?


public abstract sealed class Test
{

Page 74 of 115
public virtual void Method()
{
}
}
No, a class cannot be marked as sealed and abstract at the same time. This is
because by definition, a sealed class cannot be a base class and an abstract
class can only be a base class.
What are the 4 pillars of any object oriented programming language?
1. Abstraction
2. Inheritance
3. Encapsulation
4. Polymorphism

Do structs support inheritance?


No, structs do not support inheritance, but they can implement interfaces.

What is the main advantage of using inheritance?


Code reuse

Is the following code legal?


class ChildClass : ParentClassA, ParentClassB
{
}
No, a child class can have only one base class. You cannot specify 2 base
classes at the same time. C# supports single class inheritance only. Therefore,
you can specify only one base class to inherit from. However, it does allow
multiple interface inheritance.

What will be the output of the following code?


using System;
public class BaseClass
{
public BaseClass()
{
Console.WriteLine("I am a base class");
}
}
public class ChildClass : BaseClass
{
public ChildClass()
{
Console.WriteLine("I am a child class");
}
static void Main()
{
ChildClass CC = new ChildClass();

Page 75 of 115
}
}
Output:
I am a base class
I am a child class
This is because base classes are automatically instantiated before derived
classes. Notice the output, The BaseClass constructor executed before the
ChildClass constructor.
Will the following code compile?
using System;
public class Example
{
static void Main()
{
TestStruct T = new TestStruct();
Console.WriteLine(T.i);
}
}
public struct TestStruct
{
public int i=10;
//Error: cannot have instance field initializers in structs
}
No, a compile time error will be generated stating "within a struct declaration,
fields cannot be initialized unless they are declared as const or static"

Can a struct have a default constructor (a constructor without parameters)


or a destructor in C#?
No

Can you instantiate a struct without using a new operator in C#?


Yes, you can instantiate a struct without using a new operator

Can a struct inherit from another struct or class in C#?


No, a struct cannot inherit from another struct or class, and it cannot be the base
of a class.

Can a struct inherit from an interface in C#?


Yes

Are structs value types or reference types?


Structs are value types.

What is the base type from which all structs inherit directly?
All structs inherit directly from System.ValueType, which inherits from
System.Object.

Page 76 of 115
What is Boxing and Unboxing?
Boxing - Converting a value type to reference type is called boxing. An example
is shown below.
int i = 101;
object obj = (object)i; // Boxing

Unboxing - Converting a reference type to a value typpe is called unboxing. An


example is shown below.
obj = 101;
i = (int)obj; // Unboxing

Is boxing an implicit conversion?


Yes, boxing happens implicitly.

Is unboxing an implicit conversion?


No, unboxing is an explicit conversion.

What happens during the process of boxing?


Boxing is used to store value types in the garbage-collected heap. Boxing is an
implicit conversion of a value type to the type object or to any interface type
implemented by this value type. Boxing a value type allocates an object instance
on the heap and copies the value into the new object. Due to this boxing and
unboxing can have performance impact.

What is LINQ?
LINQ, or Language INtegrated Query, is a set of classes added to the .NET
Framework 3.5. LINQ adds a rich, standardized query syntax to .NET
programming languages that allows developers to interact with any type of data.

What are the advantages of using LINQ or Language INtegrated Query?


In any data driven application, you get data either from a Database, or an XML
file or from collection classes. Prior to LINQ, working with each data source
requires writing a different style of code. Moreover, working with external
resources like data bases, XML files involves communicating with that external
resource in some syntax specific to that resource. To retrieve data from a
database you need to send it a string that contains the SQL query to execute,
similarly, to work with an XML document involves specifying an XPath expression
in the form of a string. The idea is that using LINQ you can work with disparate
data sources using a similar style without having to know a separate syntax for
communicating with the data source (e.g., SQL or XPath) and without having to
resort to passing opaque strings to external resources.

In any data driven web application or windows application, we use database as a

Page 77 of 115
datasource for the application. In order to get data from the database and display
it in a web or windows application, we typically do the following.
1. Prepare your SQL Statements.
2. Execute SQL Statements against the database.
3. Retrieve the results.
4. Populate the Business Objects.
5. Display the Data in the Web Form or Windows From.

In order to send a query to the database we must first establish a connection to


the database. We then must encode the logic - the SQL query, its parameters,
and the parameters' values - into strings that are supplied to the SqlCommand
object. And because these inputs are encoded into opaque strings, there is no
compile-time error checking and very limited debugging support. For example, if
there is a spelling mistake in the SELECT query causing the Customets table
name to be misspelled, this typographical error won't show up until runtime when

Page 78 of 115
this page is viewed in a web browser. These typographical errors are easy to
make as there is no IntelliSense support. When we use LINQ, Visual Studio
would display an error message alerting us about the incorrect table name.

Another mismatch between the programming language and the database is that
the data returned by the database is transformed for us into objects accessible
through the SqlDataReader, but these objects are not strongly-typed objects like
we'd like. To get this data into strongly-typed objects we must write code
ourselves that enumerates the database results and populates each record into a
corresponding object.

LINQ was designed to address all these issues. LINQ also offers a unified syntax
for working with data, be it data from a database, an XML file, or a collection of
objects. With LINQ you don't need to know the intricacies of SQL, the ins and
outs of XPath, or various ways to work with a collection of objects. All you need
be familiar with is LINQ's classes and the associated language enhancements
centered around LINQ.

In other words, LINQ provides type safety, IntelliSense support, compile-time


error checking, and enhanced debugging scenarios when working with different
datasources.

What are the three main components of LINQ or Language INtegrated


Query?
1. Standard Query Operators
2. Language Extensions
3. LINQ Providers

How are Standard Query Operators implemented in LINQ?


Standard Query Operators are implemented as extension methods in .NET
Framework. These Standard Query Operators can be used to work with any
collection of objects that implements the IEnumerable interface. A class that
inherits from the IEnumerable interface must provide an enumerator for iterating
over a collection of a specific type. All arrays implement IEnumerable. Also, most
of the generic collection classes implement IEnumerable interface.

How are Standard Query Operators useful in LINQ?


Standard Query Operators in LINQ can be used for working with collections for
any of the following and more.
1. Get total count of elements in a collection.
2. Order the results of a collection.
3. Grouping.
4. Computing average.
5. Joining two collections based on matching keys.

Page 79 of 115
6. Filter the results

List the important language extensions made in C# to make LINQ a reality?


1. Implicitly Typed Variables
2. Anonymous Types
3. Object Initializers
4. Lambda Expressions

What is the purpose of LINQ Providers in LINQ?


LINQ Providers are a set of classes that takes a LINQ query and dynamically
generates a method that executes an equivalent query against a specific data
source.

What are the four LINQ Providers that .NET Framework ships?
1. LINQ to Objects - Executes a LINQ query against a collection of objects
2. LINQ to XML - Executes an XPATH query against XML documents
3. LINQ to SQL - Executes LINQ queries against Microsoft SQL Server.
4. LINQ to DataSets - Executes LINQ queries against ADO.NET DataSets.

Write a program using LINQ to find the sum of first 5 prime numbers?

Click here for all C# Interview Questions

Click here for all ASP.NET Interview Questions

What is the difference between arrays in C# and arrays in other


programming languages?
Arrays in C# work similarly to how arrays work in most other popular
languages There are, however, a few differences as listed below

1. When declaring an array in C#, the square brackets ([]) must come

Page 80 of 115
after the type, not the identifier. Placing the brackets after the
identifier is not legal syntax in C#.

int[] IntegerArray; // not int IntegerArray[];

2. Another difference is that the size of the array is not part of its type
as it is in the C language. This allows you to declare an array and
assign any array of int objects to it, regardless of the array's length.

int[] IntegerArray; // declare IntegerArray as an int array of any size


IntegerArray = new int[10]; // IntegerArray is a 10 element array
IntegerArray = new int[50]; // now IntegerArray is a 50 element array

What are the 3 different types of arrays that we have in C#?


1. Single Dimensional Arrays
2. Multi Dimensional Arrays also called as rectangular arrays
3. Array Of Arrays also called as jagged arrays

Are arrays in C# value types or reference types?


Reference types.

What is the base class for all arrays in C#?


System.Array

How do you sort an array in C#?


The Sort static method of the Array class can be used to sort array
items.

Give an example to print the numbers in the array in


descending order?
using System;
namespace ConsoleApplication
{
class Program
{
static void Main()
{
int[] Numbers = { 2, 5, 3, 1, 4 };
//Print the numbers in the array without sorting
Console.WriteLine("Printing the numbers in the array without
sorting");
foreach (int i in Numbers)
{
Console.WriteLine(i);

Page 81 of 115
}
//Sort and then print the numbers in the array
Console.WriteLine("Printing the numbers in the array after sorting");
Array.Sort(Numbers);
foreach (int i in Numbers)
{
Console.WriteLine(i);
}
//Print the numbers in the array in desceding order
Console.WriteLine("Printing the numbers in the array in desceding
order");
Array.Reverse(Numbers);
foreach (int i in Numbers)
{
Console.WriteLine(i);
}
}
}
}

What property of an array object can be used to get the total


number of elements in an array?
Length property of array object gives you the total number of
elements in an array. An example is shown below.
using System;
namespace ConsoleApplication
{
class Program
{
static void Main()
{
int[] Numbers = { 2, 5, 3, 1, 4 };
Console.WriteLine("Total number of elements = " +Numbers.Length);
}
}
}

Give an example to show how to copy one array into another


array?
We can use CopyTo() method to copy one array into another array. An
example is shown below.
using System;
namespace ConsoleApplication
{

Page 82 of 115
class Program
{
static void Main()
{
int[] Numbers = { 2, 5, 3, 1, 4 };
int[] CopyOfNumbers=new int[5];
Numbers.CopyTo(CopyOfNumbers,0);
foreach (int i in CopyOfNumbers)
{
Console.WriteLine(i);
}
}
}
}

What is an HTTP Handler?


An ASP.NET HTTP handler is the process (frequently referred to as
the "endpoint") that runs in response to a request made to an
ASP.NET Web application. The most common handler is an ASP.NET
page handler that processes .aspx files. When users request an .aspx
file, the request is processed by the page through the page handler.
You can create your own HTTP handlers that render custom output to
the browser.

What is HTTP module?


An HTTP module is an assembly that is called on every request that
is made to your application. HTTP modules are called as part of the
ASP.NET request pipeline and have access to life-cycle events
throughout the request. HTTP modules let you examine incoming and
outgoing requests and take action based on the request.

What is the interface that you have to implement if you have to


create a Custom HTTP Handler?
Implement IHttpHandler interface to create a synchronous handler.
Implement IHttpAsyncHandler to create an asynchronous handler.

What is the difference between asynchronous and synchronous


HTTP Handlers?
A synchronous handler does not return until it finishes processing
the HTTP request for which it is called.

An asynchronous handler runs a process independently of sending a


response to the user. Asynchronous handlers are useful when you

Page 83 of 115
must start an application process that might be lengthy and the user
does not have to wait until it finishes before receiving a response from
the server.

Which class is responsible for receiving and forwarding a


request to the appropriate HTTP handler?
IHttpHandlerFactory Class

Can you create your own custom HTTP handler factory class?
Yes, we can create a custom HTTP handler factory class by creating a
class that implements the IHttpHandlerFactory interface.

What is the use of HTTP modules?


HTTP modules are used to implement various application features,
such as forms authentication, caching, session state, and client script
services.

What is the difference between HTTP modules and HTTP


handlers?
An HTTP handler returns a response to a request that is identified by
a file name extension or family of file name extensions. In contrast, an
HTTP module is invoked for all requests and responses. It subscribes
to event notifications in the request pipeline and lets you run code in
registered event handlers. The tasks that a module is used for are
general to an application and to all requests for resources in the
application.

What is the common way to register an HTTP module?


The common way to register an HTTP module is to have an entry in
the application's Web.config file.

Much of the functionality of a module can be implemented in a


global.asax file. When do you create an HTTP module over
using Global.asax File?
You create an HTTP module over using Global.asax file if the
following conditions are true

1. You want to re-use the module in other applications.


2. You want to avoid putting complex code in the Global.asax file.
3. The module applies to all requests in the pipeline.
What are the best practices to follow to secure connection strings in an
ASP.NET web application?
1. Always store connection strings in the site's Web.config file. Web.config is very
secure. Users will not be able to access web.config from the browser.

Page 84 of 115
2. Do not store connection strings as plain text. To help keep the connection to
your database server secure, it is recommended that you encrypt connection
string information in the configuration file.
3. Never store connection strings in an aspx page.
4. Never set connection strings as declarative properties of the SqlDataSource
control or other data source controls.

Why is "Connecting to SQL Server using Integrated Security" considered a


best practice?
Connecting to SQL Server using integrated security instead of using an explicit
user name and password, helps avoid the possibility of the connection string
being compromised and your user ID and password being exposed.

What is the advantage of storing an XML file in the applications App_Data


folder? The contents of the App_Data folder will not be returned in response to
direct HTTP requests.

What is Script injection?


A script injection attack attempts to send executable script to your application
with the intent of having other users run it. A typical script injection attack sends
script to a page that stores the script in a database, so that another user who
views the data inadvertently runs the code.

What is SQL injection?


A SQL injection attack attempts to compromise your database by creating SQL
commands that are executed instead of, or in addition to, the commands that you
have built into your application.

What are the best practices to keep in mind when accepting user input on a
web application?
1. Always use validation controls whenever possible to limit user input to
acceptable values.
2. Always check the IsValid property of the aspx page. Run the server side code
only if the IsValid property value is true. A value of false means that one or more
validation controls have failed a validation check.
3. Always perform server side validation irrespective of client side validation
being performed or not. This will protect your web application even if the client
has by passed the client side validation by disabling javascript in the web
browser.
4. Also make sure to re validate user input in the business logic layer of your
application.

What are the steps to follow to avoid Script Injection attacks?


1. Encode user input with the HtmlEncode method. This method turns HTML into
its text representation.
2. If you are using the GridView control with bound fields, set the BoundField

Page 85 of 115
object's HtmlEncode property to true. This causes the GridView control to encode
user input when the row is in edit mode.

What are the steps to follow to avoid SQL Injection attacks?


Always use parameterized queries or stored procedures instead of creating SQL
commands by concatenating strings together.

Can you encrypt view state data of an aspx page?


Yes, you encrypt view state data of an aspx page by setting the page's
ViewStateEncryptionMode property to true.

When inheriting from a base class, whether the derived class inherits the destructor and constructor fr
base class?
Posted by: Santosh.impossible | Show/Hide Answer
No, On inheriting from a base class the derived class inherits the only the mem
including the code except the destructor and constructor of the base class.

What are Generics?


Posted by: Poster | Show/Hide Answer
Generics means parametrized types. A class, structure, interface, delegates that opera
a parametrized type is called gen

The ability to create type-safe code in which type-mismatch errors are caught at c
time rather than run time is the key advantage of the Generics. So using generics
class, interface, methods or delegates avoids run time errors as it is caught at the c
time

In order to use Generics, we need to work with System.Collections.Generic name

IList<>, IEnumerable, IEnuerator<>, IComparer<>, ICollection<> and IDictionary are


of the frequently used generics objects.

Write the syntax of foreach loop with hashtable and get the key, value pair from the hashtable?
Posted by: Peermohamedmydeen | Show/Hide Answer
HashTable ht = new HashTa
ht.Add(1,"A");
ht.Add(2,"B");
ht.Add(3,"C");

foreach(DictionaryEntry de in
{

Page 86 of 115
Console.WriteLine(string.Format("Key : {0} Value:
de.Key.ToString(),de.Value.ToString()));

What is Closed constructed type and Open constructed type?


Posted by: Poster | Show/Hide Answer
Closed constructed type and open constructed type is term that is used while instantia
object.

For ex

class myClassO<T>

Class MyClassC<int>

In above code class myClassO is the open constructed type as we can pass any t
parameter while instantiating the myClassO o

myClassO<int> i = new myClassO<int>(20); // Correct

myClassO<string> i = new myClassO<strubg>('my string"); // Correct

You can notice that I can pass either integer or string in the myClassO insntiation as
the generic

myClassC is the closed constructed type as I have specified the type of argument
passed in the myClassC instant

Page 87 of 115
myClassC<int> i = new myClassC<int>(20); // Correct

myClassC<string> i = new myClassC<strubg>('my string"); // InCorrect

Example for Compile time Polymorphism and Example for Run time Polymorphism?
Posted by: Peermohamedmydeen | Show/Hide Answer
Example of Compile Time Polymorphism - Method Overlo
Example of Run Time Polymorphism - Method Overriding

Why C# is called Strongly Typed Language?


Posted by: Poster | Show/Hide Answer
C# is called Strongly Typed Language becausen its type rules are very strict. For ex
you can't called a function that is designed to call Integer with a string or decimal.
want to do so then you will have to explicitly convert them to integer.

String is a Class then why can't you create a object for the string like this String str = new String();
Posted by: Esakkriajak | Show/Hide Answer
Since String is sealed class we can't create object for it.

Explain About ref and out parameters?


Posted by: BangaruBabu | Show/Hide Answer
ref param
Ref is key
it must be used along with actual and formal argum
ref variables must be initialized before passing to a fu

out param
It is very similar to call by Refe
Out is a Key
Which must be used along with actual and formal argum
Out variables are not require to initialize, the initialized value will not be passed
reference will be passed.

Some facts about Virtual methods.


Posted by: Raja | Show/Hide Answer
Virtual keyword is used to declare a method inside the base class that can be overr

Following conditions are applied to a virtual m

Page 88 of 115
1. Virtual method can not be declared as P
2. Virtual method can not be declared as
3. Virtual method may or may not be overr
4. In order to override the virtual method of the base class, Override keyword i
provided the method signature of the derived class is same as base class, even the
modifier should be
5. A Virtual method must contain the method body otherwise compiler shall throw
6. Virtual keyword is only used in base and derived class scenario where you wan
method over-ridable in the derived

Enjoy virtual keyword :)

What is the difference between IQueryable<T> and IEnumerable<T> interface?


Posted by: Raja | Show/Hide Answer
IEnumerable<T>
IEnumerable<T> is best suitable for working with in-memory colle
IEnumerable<T> doesn't move between items, it is forward only colle

IQueryable<T>
IQueryable<T> best suits for remote data source, like a database or web se
IQueryable<T> is a very powerful feature that enables a variety of interesting de
execution scenarios (like paging and composition based qu

So when you have to simply iterate through the in-memory collection, use IEnumerab
if you need to do any manipulation with the collection like Dataset and other data so
use IQueryabl

Please let me know your feedback, if any

Can we declare a class as Protected?


Posted by: Poster | Show/Hide Answer
No, a class can not be declared as Prot

A class can be declared with only following access mod

Abstract
Internal
Public
Sealed
Static
Extern (The extern modifier is used to declare a method that is implemented extern

Page 89 of 115
http://msdn.microsoft.com/en-us/library/e59b22c5(VS.80).aspx)

Thanks

Can we inherit a private class into the public class?


Posted by: Poster | Show/Hide Answer
No, In C#, a derived class can’t be more accessible than it’s base class. It means th
can't inherit a private class into a public class. So always the base class should be m
equal accessible than a derived

// Following will throw compilation

private class BaseClass

public class DerivedClass : BaseClass

// Following will compile without an

public class BaseClass

public class DerivedClass : BaseClass

Hope this helps

Page 90 of 115
Does Abstract classes contain Constructor?
Posted by: G_arora | Show/Hide Answer
NOTE: This is objective type question, Please click question title for correct answer.

what is the class used for dealing with graphics objects


Posted by: Puneet20884 | Show/Hide Answer
System.Drawing.Graphics is the class used for dealing with graphics objects

Name any two "Permission Classes" generally used while working with CAS ?
Posted by: Puneet20884 | Show/Hide Answer
1) FileIOPerm
2) UIPerm
3) SecurityPermission

Write a way to read an image from a path to a bitmap object


Posted by: Puneet20884 | Show/Hide Answer
We can directly read an image file and load it into a Bitmap object as

Bitmap myBmpObj = Bitmap.FromFile(strPath);

We can also set Image path during the Initilization of Bitmap Object. Code as given

Bitmap loBMP = new Bitmap(strPath);

Modified
Moderator3

How we can gt the values of control on the previous page in case od server.transfer method?
Posted by: Lakhangarg | Show/Hide Answer
Using Page.PreviousPage.FindControl() method.

Can we use Page.PreviousPage to get the value of controls of the previous page in case of response.Red

Page 91 of 115
Posted by: Lakhangarg | Show/Hide Answer
No, we can't use PreviousPage to find the control on previous page with response.redir

What is the page size in SQL Server?


Posted by: Lakhangarg | Show/Hide Answer
8 KB -- >
you can check this with the query
SELECT low FROM master..spt_values WHERE number = 1 AND type = 'E'

What is the main difference between RegisterStartUpScript and RegisterClientScriptBlock?


Posted by: Lakhangarg | Show/Hide Answer
RegisterStartUpScript Add the javascript code at the end of the page before the clo
form tag. while RegisterClientScriptBlock place the code at th top of the page.

Which methods are used to execute javascript code from code behind file?
Posted by: Lakhangarg | Show/Hide Answer
RegisterStartupScript and RegisterClientScriptBlock

If i will write a piece of code in finaly block, will it execute if there is an exception in try block.
Posted by: Lakhangarg | Show/Hide Answer
Yes, the code in finally block will execute.

Why 'static' keyword is used before Main()?


Posted by: Abhisek | Show/Hide Answer
Program execution starts from Main(). S it should be called before the creation of any
By using static the Main() can now be called directly through the class name and ther
need to create the object to call it. So Main() is declared as static.

What is CharEnumerator in C#?


Posted by: Raja | Show/Hide Answer
CharEnumerator is an object in C# that can be used to enumerate through
characters of a string. Below is the sample to do

string str = "my name";

CharEnumerator chs = str.GetEnumerator();

Page 92 of 115
while(chs.MoveNext())

Response.Write(chs.Current);

I would like to find all the directories of a folder How should I achieve this?
Posted by: Nishithraj | Show/Hide Answer
By Directory.GetDirectories method

Tell me one reason for dotnet doesn't have multiple inheritance


Posted by: Nishithraj | Show/Hide Answer
To avoid ambiguity and deadlocks

How can you check a nullable variable is assigned?


Posted by: Nishithraj | Show/Hide Answer
using hasvalue method

what is the syntax of a nullable variable?


Posted by: Nishithraj | Show/Hide Answer
Nullable myval=null;

I would like to check a variable as assigned or not. How can we do that?


Posted by: Nishithraj | Show/Hide Answer
Declare the variable as Nullable

What are the different compiler generated methods when a .NET delegate is compiled?
Posted by: Abhisek | Show/Hide Answer
Compilation of a .NET delegate results in a sealed class with three compiler generated methods whose
parameters and return values are dependent on the delegate declaration. The methods are,
Invoke()
BeginInvoke() and
EndInvoke().

When TimerCallback delegate is used?


Posted by: Abhisek | Show/Hide Answer

Page 93 of 115
Many application have the need to call a specific method during regular intervals. For such situations w
use the System.Threading.Timer type in conjunction with a related delegate named TimerCallback.

Which enumeration defines different PenCap in C#?


Posted by: Abhisek | Show/Hide Answer
LineCap enumeration which defines different pen cap styles as follows,

public enum LineCap

Flat, Square, Round, Triangle, NoAncher, SquareAnchor,

RoundAnchor, DiamondAnchor, ArrowAnchor, AnchorMask, Custom

What is the use of param keyword in C#?


Posted by: Abhisek | Show/Hide Answer
In C# param parameter allows us to create a method that may be sent to a set of identically typed argu
as a single logical parameter.

Which class defines different events for controls in C#?


Posted by: Abhisek | Show/Hide Answer
The "Control" class defines a number of events that are common to many controls.

What do you mean by properties in C#?


Posted by: Abhisek | Show/Hide Answer
Property acts as a cross link between the field and the method . Actually it behaves as a field. We can r
and store data from the field using property.

The compiler automatically translates the field like property into a call like special method called as 'a
. In property there are two accessor and that are used to save value and retrieve value from the field. T
properties are 'get' and 'set'.

The get property is used to retrieve a value from the field and the set property is used to assign a value
field .

Depending on there use properties are categorised into three types,

ReadWrite Property :- When both get and set properties are present it is called as ReadWrite Property

Page 94 of 115
ReadOnly Property :- When there is only get accessor it is called as ReadOnly Property.

WriteOnly Property :- When there is only set accessor, it is called as WriteOnly Property.

What are the different method parameter modifiers in C#?


Posted by: Abhisek | Show/Hide Answer
out
ref
params

What are the different Iteration Constructs in C#?


Posted by: Abhisek | Show/Hide Answer
for
foreach/in
while
do/while loop

What is the use of ?? operator in C#?


Posted by: Abhisek | Show/Hide Answer
This operator allows you to assign a value to a nullable type if the retrieved value is in

What is the CIL representation of implicit and explicit keywords in C#?


Posted by: Abhisek | Show/Hide Answer
The CIL representation is op_Implicit and op_Explicit respectively.

Which operators in C# provides automatic detection of arithmetic overflow and underflow conditions?
Posted by: Abhisek | Show/Hide Answer
'checked' and 'unchecked' keywords provide automatic detection of arithmetic overflow

What is the use of stackalloc keyword in C#?


Posted by: Abhisek | Show/Hide Answer
In an unsafe context it is used to allocate C# array directly on the stack.

Which keyword in C# is used to temporarily fix a variable so that its address may be found?
Posted by: Abhisek | Show/Hide Answer
fixed keyword

Page 95 of 115
What are the different C# preprocessor directives?
Posted by: Abhisek | Show/Hide Answer
#region , #endregion :- Used to mark sections of code tha

#define , #undef :-Used to define and undefine conditional

#if , #elif , #else , #endif :- These are used to conditionally skip sections of source

What is the use of GetInvocationList() in C# delegates?


Posted by: Abhisek | Show/Hide Answer
GetInvocationList() returns an array of System.Delegate types, each representing a p
invoked.

C# delegate keyword is derived form which namespace?


Posted by: Abhisek | Show/Hide Answer
C# delegate keyword is derived form System.MulticastDelegate.

What will be the length of string type variable which is just declared but not assigned any value?
Posted by: Virendradugar | Show/Hide Answer
As variable is not initialized and it is of reference type. So it's length will be null
exception of "System.NullReferenceException" type, if used.

How do we retrieve day, month and year from the datetime value in C#?
Posted by: Nishithraj | Show/Hide Answer
Using the methods Day,Month and Year

int day = dobDate.Day;

int month = dobDate.Month;i

nt year = dobDate.Year;

int? d = 1; Type testType = d.GetType(); will result…


Posted by: Bhakti | Show/Hide Answer
NOTE: This is objective type question, Please click question title for correct answer.

How can you make your machine shutdown from your program?

Page 96 of 115
Posted by: Bhakti | Show/Hide Answer
Process.Start("shutdown", "-s -f -t 0");

What is the use of unsafe keyword in C#?


Posted by: Abhisek | Show/Hide Answer
In C# the value can be directly referenced to a variable, so there is no need of poin
crashes the application. But C# supports pointer, that means we c

The use of pointer in C# is defined as a unsafe code. So if we want to use pointe


present in the body of unsafe declaration. But pointer does not come

Example:-

unsafe
{
int a,
a =
b =
Console.WriteLine("b= {0}",b);//returns
}

What is difference between var and Dynamic ?


Posted by: Bhakti | Show/Hide Answer
Var word was introduced with C#3.5(specifically for LINQ) while dynamic is introduced
with var keyword will get compiled and you can have all its related methods by intellis
with dynamic keyword will never get compiled. All the exceptions related to dynam
caught at runtime.

What is dynamic keyword ?


Posted by: Bhakti | Show/Hide Answer
Its newly introduced keyword of C#4.0. To indicate that all operations will be performe

What will happen if you declare a variable named "checked" with any data type?
Posted by: Virendradugar | Show/Hide Answer
Compiler will throw an error as checked is a keyword in C# So It cannot be used
keyword is used to check the overflow arithmetic checking.

What are anonymous methods?


Posted by: Bhakti | Show/Hide Answer
Anonymous methods are another way to declare delegates with inline code except nam

Page 97 of 115
Restrictions of yield in try-catch.
Posted by: Bhakti | Show/Hide Answer
While using yield keyword, mainly two restrictio
First is , we can’t use yield
Second is , we can’t place yield keyword in the catch block if try contains more than o

With yield break statement, control gets …


Posted by: Bhakti | Show/Hide Answer
NOTE: This is objective type question, Please click question title for correct answer.

What first action compiler will take on detection of iterator ?


Posted by: Bhakti | Show/Hide Answer
As soon as compiler will detect iterator, it will automatically generate current, MoveNe
IEnumerator or IEnumerator(T) type.

What is obsolete method?


Posted by: Virendradugar | Show/Hide Answer
Obsolete means old or no longer in use. We can define a method as obsolete using

[Obsolete]

public int Fun1()

//Code goes here.

or

Page 98 of 115
[Obsolete("Any user define message")] public int Fun1()

//Code goes here..

What is optional and named parameter in C#4.0?


Posted by: Bhakti | Show/Hide Answer
Optional parameter allows omitting arguments to function while named parameters
parameter
By declaring below variable you are assigning default values to second and third para
(param2 and
public void optionalParam(int Param1, int param2 = 2,

After this you can


optionalParam(1); //which will be equivalent to

Sometimes, you may need to not to pass param2. But, optionalParam(1,,3) is not va
point, named parameter comes to

You can specify argume


optionalParam(1, param3:10); //which will be
optionalParam(1,2,10);

What is the difference between a.Equals(b) and a == b?


Posted by: Chikul | Show/Hide Answer
For value types : “==” and Equals() works same way : Compare
Example:
int i =
int k=
i == k >
i.Equals(k) >

For reference types : both works


“==” compares reference – returns true if and only if both references point
"Equals" method compares object by VALUE and it will return true if the referen

Page 99 of 115
equivalent
Example:
StringBuilder sb1 = new
StringBuilder sb2 = new
sb1 == sb2 >
sb1.Equals(sb2) >

But now look at foll


String s1 =
String s2 =
In above case the results
s1 == s2 >
s1.Equals(s2) >
String is actually reference type : its a sequence of “Char” and its also immutable
behave like Value Types in
Exceptions are always

Now another interesting


int i =
byte b =
i == b >
i.Equals(b) >
So, it means Equals method compare not only value but it compares TY

Recommendation
For value types: us
For reference types: use Equals method.

What is the difference between Parse and TryParse method?


Posted by: Virendradugar | Show/Hide Answer
Parse method is used to parse any value to

For

string test =
int32
Result =

This will work fine bt what if when you are aware about the value

if

In that case if u try to use above method, .NET will throw an exception as you are tr

Page 100 of 115


integer.

TryParse is a good method if the string you are converting to an interge

if(!Int32.TryParse(test,out
{
//do
}

The TryParse method returns a boolean to denote whether the conversion has been s
the converted value through an

**declare variable iResult of Int32.

Can we define generics for any class?


Posted by: Indianengg84 | Show/Hide Answer
No, generics is not supported for the classes which deos not inherits collect class.

Which method is used to return an item from the Top of the Stack?
Posted by: Syedshakeer | Show/Hide Answer
NOTE: This is objective type question, Please click question title for correct answer.

Which method is used to reads and removes an item from the head of the Queue.
Posted by: Syedshakeer | Show/Hide Answer
NOTE: This is objective type question, Please click question title for correct answer.

Whcih method is used to add an Item on stack?


Posted by: Syedshakeer | Show/Hide Answer
NOTE: This is objective type question, Please click question title for correct answer.

Give Some Examples of Generic Classes?


Posted by: Syedshakeer | Show/Hide Answer
List<T>,Queue<T>,Stack<T>,LinkedList<T>,HashSet<T>

A Queue is a collection where elements are processed in


Posted by: Syedshakeer | Show/Hide Answer
NOTE: This is objective type question, Please click question title for correct answer.

Page 101 of 115


Which method is used to add an Item to the end of the Queue?
Posted by: Syedshakeer | Show/Hide Answer
NOTE: This is objective type question, Please click question title for correct answer.

The Items that is put in the Queue is Reads ?


Posted by: Syedshakeer | Show/Hide Answer
NOTE: This is objective type question, Please click question title for correct answer.

Can we declare an array variable with var keyword in C# 3.0?


Posted by: Raja | Show/Hide Answer
No, var keyword is used to declare implicitly typed local variable. An implicitly typ
declared the type yourself, but the c

So you can declare a local variable of any type using var keyword but you can

Correct

string[] str = { "ram", "sham" };

foreach (var s in str)

Response.Write(s + "<br />");

Wrong

var[] str = { "ram", "sham" };

foreach (var s in str)

Page 102 of 115


Response.Write(s + "<br />");

This will throw "CS0246: The type or namespace name 'var' could not be found
reference?) "

For more info on var keyword see ht

Thanks

Is it possible to notify application when item is removed from cache ?


Posted by: Bhakti | Show/Hide Answer
Yes.
You can use CacheItemRemovedCallback delegate defining signature for event h

For an

HttpRuntime.Cache.Insert(

"CacheItem1", //insert cache item

"",

null,

Cache.NoAbsoluteExpiration,

new TimeSpan(0, 0, 15),

CacheItemPriority.Default,

new CacheItemRemovedCallback(RemovalMethod)); //define method


from cache

the method will

Page 103 of 115


private static string RemovedAt = string.Empty;

public static void RemovalMethod(String key, object value, //method


when cache item is deleted

CacheItemRemovedReason removedReason)

RemovedAt = "Cache Item Removed at: " + DateTime.Now.ToString();

How can you cache Multiple Versions of a Page?


Posted by: Bhakti | Show/Hide Answer
Using output cache you can cache multip

We can
- @ OutputCache directive at design time d
OR
- Response.Cacheclass at runtime

With @ OutputCache directive four parameters of VaryByParam , VaryByControl, Va


depending on query string, control value, request's HTTP he
For an

To turn
Declarative

<%@ OutputCache Location="None" VaryByParam="None" %>

Programmatic

Response.Cache.SetCacheability(HttpCacheability.NoCache);

To cache the output for each HTTP request th


Declarative

Page 104 of 115


<%@ OutputCache duration="60" varybyparam=" ID" %>

Programmatic

Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));

Response.Cache.SetCacheability(HttpCacheability.Public);

Response.Cache.VaryByParams["ID"] = true;

You have to make user to enter just integer values with TextBox. Can you do this with CompareValida
Posted by: Bhakti | Show/Hide Answer
Yes. With the validator control, you need to set type attribute to the desired data
DataTypeCheck.

<asp:CompareValidator ID="CompareValidator1" ControlToValidate="TextBox1"

runat="server" ErrorMessage="CompareValidator"></asp:CompareV

How to Find Number of Days for provided date range?


Posted by: Bhakti | Show/Hide Answer
Code extract

TimeSpan DayDifference = Convert.ToDateTime("2009-1-7").Subtract(Convert.

To find the difference of the days, here we have used Subtract method. The Subtra
Hence, to get the exact number of days for the date range we

Response.Write("Number of Days : " + DayDifference.Days+1);

What is Delay Signing ?

Page 105 of 115


Signing the assemble at the end of development phase is called delay signing. We
time as a developer we may not have the access of private key of the company to sig
the “Delay signing” option for that assembly

To open the project property window , we need to Right click on sol

What is GAC?

Global Assembly Cache in .NET Framework acts as the central place for registering as
To avoid the name conflict “Strong name” is used with each and every assembly to sto
components
a. Assembly
b. Assembly
c. Culture
d. Public
“Sn.exe” is used to create the strong name of an assembly. Gacuti
GAC is located under :\Windows\Assembly folder.

What is Sealed Class ?

Sealed class is a class which can’t inherited any more. “Sealed”


keyword is used to make class Sealed. So, once we define a class
using Sealed that can’t be inherited.

What are Properties in .NET, What are the advantages of using Properties in .NET, How to declare a p

Page 106 of 115


Show/Hide Answer

The primary building block of any .NET object is Data Members. Data members hold
members. Properties provide control access to the f

Each Properties in .NET is provided with two methods, Get / Set. Get is called whene
while Set is called whenever the value

It is always better to use properties to be exposed publicly from outside rather than
validate the data before setting it to the member or determine what value to be sent b
very

Say for

// Private variable for the property


private string m_CategoryName = string.Empty;
// Declare the property now
public string CategoryName
{
get { return m_CategoryName; }
set { m_CategoryName = value; }
}

// Private variable for the property


private MyClass mfield = null;
// Declare the property now
public MyClass MyProperty
{
get
{
this.mfield = this.mfield ?? new MyClass(); // Null coalesce
return this.mfield;
}
set
{
if (value == null)
{
//throw exception
}
else this.mfield = value;
}
}

Page 107 of 115


Here mfield is the mapped data element which is

Another way of declari

You can also declare properties

public MyClass MyProperty { get;set; }


public string CategoryName { get;set; }

Here, you can see that we have declared properties without declaring private data me
code snippet as internally, .NET declares a pr

Difference between function Overloading and Overriding ?

Show/Hide Answer

Overloading

Overloading means having functions with the same name but with different signatu
These functions can be a part of base class or derived class.

Overriding

Whereas Overriding means changing the functionality of a method without changing th


creating a similar function in derived class. This is

Base class method has to be marked with virtual keyword and we can ov

Derived class method will completly overrides base class method i.e when we refer bas
method in derived class will be called.

Example:

Page 108 of 115


// Base class
public class BaseClass
{
public virtual void Method1()
{
Console.Write("Base Class Method");
}
}
// Derived class
public class DerivedClass : BaseClass
{
public override void Method1()
{
Console.Write("Derived Class Method");
}
}
// Using base and derived class
public class Sample
{
public void TestMethod()
{
// calling the overriden method
DerivedClass objDC = new DerivedClass();
objDC.Method1();

// calling the baesd class method


BaseClass objBC = (BaseClass)objDC;
objDC.Method1();
}
}

Result
---------------------

Derived Class
Derived Class Method

General Syntax for Sealed Class is:

/// <summary>
/// Syntax For Sealed Class
/// </summary>

Page 109 of 115


sealed class DemoSealedClass
{
// Implementation of the Class
}

Let’s have a look one example of sealed class,

/// <summary>
/// Sealed Class Use
/// </summary>
class TestClass
{
static void Main(string[] args)
{
SealedClassDemo objsealed = new SealedClassDemo();
int total = objsealed.Add(6, 5);
Console.WriteLine("Result = " + total.ToString());
}
}

/// <summary>
/// Sealed Class
/// </summary>
sealed class SealedClassDemo
{
public int Add(int x, int y)
{
return x + y;
}
}

Above example showing how we can access a sealed class method.


But we can’t inherit the SealedClassDemo Class any more. The main
advantage of sealed class is used to restrict your class boundaries. So
Sealed class can be an derived class but can’t never be an base class
as this can’t be inherited more. Even we can’t make an abstract class
as sealed or vice versa. This will give you following compilation error.

Page 110 of 115


1. What are Sealed Classes in C#?

Ans. The sealed modifier is used to prevent derivation from a class. A


compile-time error occurs if a sealed class is specified as the base
class of another class. (A sealed class cannot also be an abstract class)

2. What is Polymorphism? How does VB.NET/C# achieve


polymorphism?

class Token
{
public string Display()
{
//Implementation goes here
return "base";
}
}
class IdentifierToken:Token
{
public new string Display() //What is the use of new keyword
{
//Implementation goes here
return "derive";
}
}
static void Method(Token t)
{
Console.Write(t.Display());

Page 111 of 115


}
public static void Main()
{
IdentifierToken Variable=new IdentifierToken();
Method(Variable); //Which Class Method is called here
Console.ReadLine();
}
For the above code What is the "new" keyword and Which Class
Method is
called here
A: it will call base class Display method
class Token
{
public virtual string Display()
{
//Implementation goes here
return "base";
}
}
class IdentifierToken:Token
{
public override string Display() //What is the use of new keyword
{
//Implementation goes here
return "derive";
}
}
static void Method(Token t)
{
Console.Write(t.Display());
}
public static void Main()
{
IdentifierToken Variable=new IdentifierToken();
Method(Variable); //Which Class Method is called here
Console.ReadLine();
}
A: Derive

3. In which Scenario you will go for Interface or Abstract Class?

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

Page 112 of 115


from classes. Even though class inheritance allows your classes to
inherit implementation from a base class, it also forces you to make
most of your design decisions when the class is first published.
Abstract classes are useful when creating components because they
allow you specify an invariant level of functionality in some methods,
but leave the implementation of other methods until a specific
implementation of that class is needed. They also version well,
because if additional functionality is needed in derived classes, it can
be added to the base class without breaking code.

4. Interfaces vs. Abstract Classes

Ans. Feature Interface Abstract class


Multiple inheritance A class may implement several interfaces. A class
may extend only one abstract class.
Default implementation An interface cannot provide any code at all,
much less default code. An abstract class can provide complete code,
default code, and/or just stubs that have to be overridden.
Constants Static final constants only, can use them without
qualification in classes that implement the interface. On the other paw,
these unqualified names pollute the namespace. You can use them and
it is not obvious where they are coming from since the qualification is
optional. Both instance and static constants are possible. Both static
and instance intialiser code are also possible to compute the
constants.
Third party convenience An interface implementation may be added to
any existing third party class. A third party class must be rewritten to
extend only from the abstract class.
is-a vs -able or can-do Interfaces are often used to describe the
peripheral abilities of a class, not its central identity, e.g. an
Automobile class might implement the Recyclable interface, which
could apply to many otherwise totally unrelated objects. An abstract
class defines the core identity of its descendants. If you defined a Dog
abstract class then Damamation descendants are Dogs, they are not
merely dogable. Implemented interfaces enumerate the general things
a class can do, not the things a class is.
Plug-in You can write a new replacement module for an interface that
contains not one stick of code in common with the existing
implementations. When you implement the interface, you start from
scratch without any default implementation. You have to obtain your
tools from other classes; nothing comes with the interface other than a
few constants. This gives you freedom to implement a radically
different internal design. You must use the abstract class as-is for the
code base, with all its attendant baggage, good or bad. The abstract

Page 113 of 115


class author has imposed structure on you. Depending on the
cleverness of the author of the abstract class, this may be good or
bad. Another issue that's important is what I call "heterogeneous vs.
homogeneous." If implementors/subclasses are homogeneous, tend
towards an abstract base class. If they are heterogeneous, use an
interface. (Now all I have to do is come up with a good definition of
hetero/homogeneous in this context.) If the various objects are all of-
a-kind, and share a common state and behavior, then tend towards a
common base class. If all they share is a set of method signatures,
then tend towards an interface.
Homogeneity If all the various implementations share is the method
signatures, then an interface works best. If the various
implementations are all of a kind and share a common status and
behavior, usually an abstract class works best.
Maintenance If your client code talks only in terms of an interface, you
can easily change the concrete implementation behind it, using a
factory method. Just like an interface, if your client code talks only in
terms of an abstract class, you can easily change the concrete
implementation behind it, using a factory method.
Speed Slow, requires extra indirection to find the corresponding
method in the actual class. Modern JVMs are discovering ways to
reduce this speed penalty. Fast
Terseness The constant declarations in an interface are all presumed
public static final, so you may leave that part out. You can't call any
methods to compute the initial values of your constants. You need not
declare individual methods of an interface abstract. They are all
presumed so. You can put shared code into an abstract class, where
you cannot into an interface. If interfaces want to share code, you will
have to write other bubblegum to arrange that. You may use methods
to compute the initial values of your constants and variables, both
instance and static. You must declare all the individual methods of an
abstract class abstract.
Adding functionality If you add a new method to an interface, you
must track down all implementations of that interface in the universe
and provide them with a concrete implementation of that method. If
you add a new method to an abstract class, you have the option of
providing a default implementation of it. Then all existing code will
continue to work without change.

see the code


interface ICommon
{
int getCommon();
}

Page 114 of 115


interface ICommonImplements1:ICommon
{
}
interface ICommonImplements2:ICommon
{
}
public class a:ICommonImplements1,ICommonImplements2
{
}

Page 115 of 115

Potrebbero piacerti anche