Monday, June 30, 2008

Object Oriented Programming

(B) What is Object Oriented Programming ?
It is a problem solving technique to develop software systems.It’s a technique to think
real world in terms of objects.Object maps the software model to real world concept.These
objects have responsibilities and provide services to application or other objects.
(B) What’s a Class ?
A class describes all the attributes of objects , as well as the methods that implement the
behavior of member objects.Its a comprehensive data type which represent a blue print
of objects.It’s a template of object.
(B) What’s a Object ?
It’s a basic unit of a system.An object is an entity that has attributes, behavior, and
identity. Objects are members of a class.Attributes and behavior of an object are defined
by the class definition.
(A) What’s the relation between Classes and Objects ?
They look very much same but are not same.Class is a definition , while object is a
instance of the class created.Class is a blue print while objects are actual objects existing
in real world.Example we have class CAR which has attributes and methods like
Speed,Brakes,Type of Car etc.Class CAR is just a prototype , now we can create real time
objects which can be used to provide functionality . Example we can create a Maruti car
object with 100 km speed and urgent brakes.
(B) What are different properties provided by Objectoriented
systems ?
Twist :- Can you explain different properties of Object Oriented Systems?
Note:- Difference between abstraction and encapsulation is one of the favorite interview
question and quiet confusing as both the terminology look alike.Best is if you can
brainstorm with your friends or do a little reading.
Following are characteristic’s of Object Oriented System’s :-
* Who motivates you ?
It allows complex real world to be represented in simplified manner.Example color is
abstracted to RGB.By just making the combination of these three colors we can achieve
any color in world.It’s a model of real world or concept.
The process of hiding all the internal details of an object from the outside world.
Communication using messages
When application wants to achieve certain task it can only be done using combination of
objects.A single object can not do all the task.Example if we want to make order processing
form. We will use Customer object , Order object , Product object and Payment object to
achieve this functionality.In short these objects should communicate with each other.This
is achieved when objects send messages to each other.
Object lifetime
All objects have life time.Objects are created , initialized , necessary functionalities are
done and later the object is destroyed.Every object have there own state and identity ,
which differ from instance to instance.
Class hierarchies (Inheritance and aggregation)
Twist :- What’s difference between Association , Aggregation and Inheritance relationships?
In object oriented world objects have relation and hierarchies in between them.There are
basically three kind of relationship in Object Oriented world :-
This is the simplest relationship between objects.Example every customer has sales.So
Customer object and sales object have a association relation between them.
This is also called as composition model.Example in order to make a “Accounts” class it
has use other objects example “Voucher”,”Journal” and “Cash” objects.So accounts class
is aggregation of these three objects.
*Which university are your from ?
Hierarchy is used to define more specialized classes based on a preexisting generalized
class.Example we have VEHICLE class and we can inherit this class make more specialized
class like CAR, which will add new attributes and use some existing qualities of the
parent class.Its shows more of a parent-child relationship .This kind of hierarchy is called
When inheritance is used to extend a generalized class to a more specialized class,it includes
behavior of the top clas(Generalized class).The inheriting class often implement a behavior
that can be somewhat different than the generalized class, but the name of the behavior
can be same.It is important that a given instance of an object use the correct behavior,
and the property of polymorphism allows this to happen automatically.
(B) How can we acheive inheritance in VB.NET ?
Note:- The following explanation is for VB.NET
Inheritance is achieved by using “Inherits” keyword in VB.NET (For C# it is “:”).Simple
Sample is provided in CD for understanding inheritance in folder
“WindowsApplicationInheritance”.There are two classes one is the parent “ClsParent”
and second is the child “ClsChild”.Parent class has a string which has to parsed for junk
data “@” and “/”.ClsParent has the functionality which parses only cleans up
“@”.”ClsChild” then inherits from parent and adds extra functionality by parsing “/”.
Public Class ClsParent
Protected strData As String = “jksdhkj@dadad///ajkdhsjakd”
Public Function Parse() As String
Dim PstrData As String
PstrData = strData
PstrData = Replace(PstrData, “@”, “”)
Return PstrData
End Function
Public Function GetActualString() As String
Return strData
End Function
End Class
Above is the source which parses only “@” of strData variable.
* What gives your greatest satisfaction in software profession ?
Public Class ClsChild
Inherits ClsParent
‘ this is child and a special parse function is added which will
also parse “/”
Public Function ParseBackSlash()
Dim PstrData As String
PstrData = Me.Parse()
PstrData = Replace(PstrData, “/”, “”)
Return PstrData
End Function
End Class
Above is the source code for “ClsChild” which does the remaining work.It adds extra
functionality by parsing “/” junk character’s of the data.
Note:- Strdata was accessible only because it was defined as protected in the parent class.
Figure :- 6.1 Inheritance in action
(I) What are abstract classes ?
Following are features of a abstract class :-
√ You can not create a object of abstract class
* How would you describe yourself ?
√ Abstract class is designed to act as a base class (to be inherited by other classes).
Abstract class is a design concept in program development and provides a
base upon which other classes are built.
√ Abstract classes are similar to interfaces. After declaring an abstract class, it
cannot be instantiated on it's own, it must be inherited.
√ In VB.NET abstract classes are created using “MustInherit” keyword.In C#
we have “Abstract” keyword.
√ Abstract classes can have implementation or pure abstract methods which
should be implemented in the child class.
Note:- In order to understand the concept simple sample of add and multiply functionality
is implemented in “WindowsAbstract” folder in CD.
From interview point of view just saying using “MustInherit” keyword is more than enough
to convince that you have used abstract classes.But to clear simple fundamental let’s try
to understand the sample code.There are two classes one is “ClsAbstract” class and other
is “ClsChild” class.”ClsAbstract” class is a abstract class as you can see the mustinherit
keyword.It has one implemented method “Add” and other is abstract method which has
to be implemented by child class “MultiplyNumber”.In the child class we inherit the
abstract class and implement the multiplynumber function.
Definitely this sample does not take out actually how things are implemented in live
projects.Basically you put all your common functionalities or half implemented
functionality in parent abstract class and later let child class define the full functionality
of the abstract class.Example i always use abstract class with all my SET GET properties
of object in abstract class and later make specialize classes for insert,update,delete for
the corresponding entity object.
Public MustInherit Class ClsAbstract
‘ use the mustinherit class to declare the class as abstract
Public Function Add(ByVal intnum1 As Integer, ByVal intnum2 As
Integer) As Integer
Return intnum1 + intnum2
End Function
‘ left this seconf function to be completed by the inheriting
Public MustOverride Function MultiplyNumber(ByVal intnum1 As
Integer, ByVal intnum2 As Integer) As Integer
End Class
* What type of environment you are looking for ?
Public Class ClsChild
Inherits ClsAbstract
‘ class child overrides the Multiplynumber function
Public Overrides Function MultiplyNumber(ByVal intnum1 As
Integer, ByVal intnum2 As Integer) As Integer
Return intnum1 * intnum2
End Function
End Class
Figure :- 6.2 Abstract classes in action
My attitude towards abstract class has been that i put all my common functionality in
abstract class.
(B) What’s a Interface ?
Interface is a contract that defines the signature of the functionality.So if a class is
implementing a interface it says to the outer world , that it provides specific behavior .
Example if a class is implementing Idisposable interface that means it has a functionality
to release unmanaged resources . Now external objects using this class knows that it has
contract by which it can dispose unused unmanaged objects.
√ Single Class can implement multiple interfaces.
√ If a class implements a interface then it has to provide implementation to all
its methods.
Note:- In CD sample “WindowsInterFace” is provided , which has a simple interface
In sample there are two files.One has the interface definition and other class implements
the interface.Below is the source code “IInterface” is the interface and “ClsDosomething”
implements the “IInterface”.This sample just displays a simple message box.
Public Interface IInterFace
Sub DoSomething()
End Interface
Public Class ClsDoSomething
Implements IInterFace
Public Sub DoSomething() Implements
MsgBox(“Interface implemented”)
End Sub
End Class
Figure:- 6.3 Interface in action
* Do you have any experience in creating Use cases , requirement documents etc ?
(A) What is difference between abstract classes and
Following are the differences between abstract and interfaces :-
√ Abstract classes can have concrete methods while interfaces have no methods
√ Interfaces do not come in inheriting chain , while abstract classes come in
(B) What is a delegate ?
Delegate is a class that can hold a reference to a method or a function.Delegate class has
a signature and it can only reference those methods whose signature is compliant with the
class.Delegates are type-safe functions pointers or callbacks.
Below is a sample code which shows a example of how to implement delegates.
Public Class FrmDelegates
Inherits System.Windows.Forms.Form
Public Delegate Sub DelegateAddString()
Private Sub FrmDelegates_Load(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub AddString()
lstDelegates.Items.Add(“Running AddString() method”)
End Sub
Private Sub cmdDelegates_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles cmdDelegates.Click
Dim objDelegateAddString As DelegateAddString
objDelegateAddString = AddressOf AddString
End Sub
End Class
In the above there is a method called “AddString()” which adds a string to a listbox.You
can also see a delegate declared as :-
Public Delegate Sub DelegateAddString()
This delegate signature is compatible with the “AddString” method.When i mean
compatibility that means that there return types and passing parameter types are same.Later
in command click of the button object of the Delegate is created and the method pointer
is received from “AddressOf ” keyword.Then by using the “Invoke” method the method
is invoked.
Figure :- 6.4 Delegate in Action
(B) What are event’s ?
As compares to delegates events works with source and listener methodology . So listener’s
who are interested in receiving some events they subscribe to the source.Once this
subscription is done the source raises events to all of it’s listener when needed.One source
can have multiple listeners.
In example sample given below class “ClsWithEvents” is a event source class , which has
a event “EventAddString()”.Now the listener’s who are interested in receiving this event’s
they can subscribe to this event.In class “FrmWithEvents” you can see the handles clause
which is associated with the “mobjClsWithEvents” objects.
Public Class ClsWithEvents
Event EventAddString(ByVal Value As String)
Public Sub AddString()
RaiseEvent EventAddString(“String added by Event”)
End Sub
End Class
*How well do you work with people? Do you prefer working alone or in teams?
Public Class FrmWithEvents
Inherits System.Windows.Forms.Form
Private WithEvents mobjClsWithEvents As New ClsWithEvents()
Private Sub FrmWithEvents_Load(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub mobjClsWithEvents_EventAddString(ByVal Value As
String) Handles mobjClsWithEvents.EventAddString
End Sub
Private Sub CmdRunEvents_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles CmdRunEvents.Click
End Sub
End Class
Figure :- 6.5 Events in action
* Describe the best project manager you've ever had ?
(I) Do events have return type ?
No events do not have return type.
(A) Can event’s have access modifiers ?
Event’s are always public as they are meant to serve every one registering to it.But you
can access modifiers in events.You can have events with protected keyword which will
be accessible only to inherited classes.You can have private events only for object in that
(A) Can we have shared events ?
Yes you can have shared event’s note only shared methods can raise shared events.
(I) What is shadowing ?
When two elements in a program have same name , one of them can hide and shadow the
other one.So in such cases the element which shadowed the main element is referenced.
Below is a sample code , there are two classes “ClsParent” and “ClsShadowedParent”.In
“ClsParent” there is a variable “x” which is a integer.”ClsShadowedParent” overrides
“ClsParent” and shadows the “x” variable to a string.
Note:- In Sample CD “WindowsShadowing” is folder which has the sample code.If you
run the program you can have two output’s one which shows a integer and other which shows
a string.
Public Class ClsParent
Public x As Integer
End Class
Public Class ClsShadowedParent
Inherits ClsParent
Public Shadows x As String
End Class
* Why should i hire you ?
Figure :- 6.6 Shadowing in Action
(A) What’s difference between Shadowing and Overriding ?
Following are the differences between shadowing and overriding :-
√ Overriding redefines only the implementation while shadowing redefines the
whole element.
√ In overriding derived classes can refer the parent class element by using “ME”
keyword , but in shadowing you can access it by “MYBASE”.
(I) What’s difference between delegate and events?
√ Actually events use delegates in bottom. But they add an extra layer on the
delegates, thus forming the publisher and subscriber model.
√ As delegates are function to pointers they can move across any clients. So any
of the clients can add or remove events , which can be pretty confusing. But
events give the extra protection by adding the layer and making it a publisher
and subscriber model.
Just imagine one of your clients doing this
*Have you ever been fired or forced to resign?
c.XyzCallback = null
This will reset all your delegates to nothing and you have to keep figuring where the error
(B) If we inherit a class do the private variables also get
inherited ?
Yes the variables are inherited but can not be accessed directly by the class interface.
(B) What are different accessibility levels defined in .NET ?
Following are the five levels of access modifiers :-
√ Private : Only members of class have access.
√ Protected :-All members in current class and in derived classes can access the
√ Friend (internal in C#) :- Only members in current project have access to the
√ Protected friend (protected internal in C#) :- All members in current project
and all members in derived class can access the variables.
√ Public :- All members have access in all classes and projects.
(I) Can you prevent a class from overriding ?
If you define a class as “Sealed” in C# and “NotInheritable” in VB.NET you can inherit
the class any further.
(I) What’s the use of “MustInherit” keyword in VB.NET ?
If you want to create a abstract class in VB.NET it’s done by using “MustInherit”
keyword.This acts only as base type and can not be inherited any further.You can not
create a object of a class which is marked as “MustInherit”.
*What have your learnt from your past project experiences ?
(I) Why can not you specify accessibility modifier in
Interface ?
All elements in Interface should be public.So by default all interface elements are public
by default.
(A) What are similarities between Class and structure ?
Following are the similarities between classes and structures :-
√ Both can have constructors, methods, properties, fields, constants,
enumerations, events, and event handlers.
√ Structures and classes can implement interface.
√ Both of them can have constructors without parameter and with parameter.
√ Both can have delegates and events.
(A) What’s the difference between Class and structure’s ?
Following are the key differences between them :-
√ Structure are value types and classes are reference types.So structures use
stack and classes use heap.
√ Structures members can not be declared as protected , but class members can
be.You can not do inheritance in structures.
√ Structures do not require constructors while classes require.
√ Objects created from classes are terminated using Garbage collector.Structures
are not destroyed using GC.
(B) What does virtual keyword mean ?
That method and property can be overridden.
(B) What are shared (VB.NET)/Static(C#) variables?
Static/Shared classes are used when a class provides functionality which is not specific to
any instance.In short if you want a object to be shared between multiple instances you
will use a static/Shared class.
*What's the logic of link list ?
Following are features of Static/Shared classes :-
√ They can not be instantiated.By default a object is created on the first method
call to that object.
√ Static/Shared classes can not be inherited.
√ Static/Shared classes can have only static members.
√ Static/Shared classes can have only static constructor.
Note :- In CD there is a folder “WindowsShared” which has a sample code for shared
variables.Below is a snippet.It has a “AddCount” function which increments a static
“intCount” variable.In form there are two buttons which creates a new object and displays
the count of the static variable.Even though the object is created and destroyed , the variable
values does not change.It retains its old value.
Public Class ClsShared
Shared intCount As Integer
Public Function AddCount() As Integer
intCount = intCount + 1
Return intCount
End Function
End Class
Public Class FrmSharedClasses
Inherits System.Windows.Forms.Form
Private Sub CmdInstance1_Click(ByVal sender As System.Object, ByVal
e As System.EventArgs) Handles CmdInstance1.Click
Dim pobjClsShared As New ClsShared()
MessageBox.Show(“The count at this moment is” &
End Sub
Private Sub CmdInstance2_Click(ByVal sender As System.Object, ByVal
e As System.EventArgs) Handles CmdInstance2.Click
Dim pobjClsShared As New ClsShared()
MessageBox.Show(“The count at this moment is” &
End Sub
End Class
* Can you explain logic of binary sort ?
Figure :- 6.7 Shared/Static In Action
(B) What is Dispose method in .NET ?
.NET provides “Finalize” method in which we can clean up our resources.But relying on
this is not always good so the best is to implement “Idisposable” interface and implement
the “Dispose” method where you can put your clean up routines.
(B) Whats the use of “OverRides” and “Overridable”
keywords ?
Overridable is used in parent class to indicate that a method can be overridden.Overrides
is used in the child class to indicate that you are overriding a method
(A) Where are all .NET Collection classes located ?
System.Collection namespace has all the collection classes available in .NET.
(A) What is ArrayList ?
*Whats difference between procedural and object oriented programming ?
Array whose size can increase and decrease dynamically.Arraylist can hold item of different
types.As Arraylist can increase and decrease size dynamically you do not have to use the
REDIM keyword.You can access any item in array using the INDEX value of the array
(A) What’s a HashTable ?
Twist :- What’s difference between HashTable and ArrayList ?
You can access array using INDEX value of array , but how many times you know the
real value of index.Hashtable provides way of accessing the index using a user identified
KEY value , thus removing the INDEX problem.
(A) What are queues and stacks ?
Queue is for first-in, first-out (FIFO) structures. Stack is for last-in, first-out (LIFO)
(B) What is ENUM ?
It’s used to define constants.
(A) What is nested Classes ?
Nested classes are classes with in classes.In sample below “ClsNested” class has a
“ChildNested” class nested inside it.
Public Class ClsNested
Public Class ChildNested
Public Sub ShowMessage()
MessageBox.Show(“Hi this is nested class”)
End Sub
End Class
End Class
This is the way we can instantiate the nested class and make the method call.
Dim pobjChildNested As New ClsNested.ChildNested()
Note:-In CD the above sample is provided in “WindowsNestedClasses”.
(B)What’s Operator Overloading in .NET?
It provides a way to define and use operators such as +, -, and / for user-defined classes
or structs. It allows us to define/redefine the way operators work with our classes and
structs. This allows programmers to make their custom types look and feel like simple
types such as int and string.
VB.NET till now does not support operator overloading. Operator overloading is done
by using the “Operator” keyword.
Note:- Operator overloading is supported in VB.NET 2005
(I) In below sample code if we create a object of class2
which constructor will fire first ?
Public Class Class1
Sub New()
End Sub
End Class
Public Class class2
Inherits Class1
Sub New()
End Sub
End Class
* I leave this to the readers......
(B)What’s the significance of Finalize method in .NET?
.NET Garbage collector does almost all clean up activity for your objects. But unmanaged
resources (ex: - Windows API created objects, File, Database connection objects, COM
objects etc) is outside the scope of .NET framework we have to explicitly clean our
resources. For these types of objects .NET framework provides Object.Finalize method
which can be overridden and clean up code for unmanaged resources can be put in this
(A)Why is it preferred to not use finalize for clean up?
Problem with finalize is that garbage collection has to make two rounds in order to remove
objects which have finalize methods.
Below figure will make things clear regarding the two rounds of garbage collection rounds
performed for the objects having finalized methods.
In this scenario there are three objects Object1, Object2 and Object3. Object2 has the
finalize method overridden and remaining objects do not have the finalize method
Now when garbage collector runs for the first time it searches for objects whose memory
has to freed. He sees three objects but only cleans the memory for Object1 and Object3.
Object2 it pushes to the finalization queue.
Now garbage collector runs for the second time. He see’s there are no objects to be freed
and then checks for the finalization queue and at this moment it clears object2 from the
So if you notice that object2 was freed from memory in the second round and not first.
That’s why the best practice is not to write clean up Non.NET resources in Finalize
method rather use the DISPOSE.
* Where you a part of some unsuccessful projects , then why was the project unsucessful ?
Figure :- 6.8 Garbage collection in actions
(I)How can we suppress a finalize method?
GC.SuppressFinalize ()
(B)What’s the use of DISPOSE method?
Dispose method belongs to IDisposable interface. We had seen in the previous section
how bad it can be to override the finalize method for writing the cleaning of unmanaged
resources. So if any object wants to release its unmanaged code best is to implement
IDisposable and override the Dispose method of IDisposable interface. Now once your
class has exposed the Dispose method it’s the responsibility of the client to call the
Dispose method to do the cleanup.
(A)How do I force the Dispose method to be called
automatically, as clients can forget to call Dispose method?
Note :- I admire this question.
Call the Dispose method in Finalize method and in Dispose method suppress the finalize
method using GC.SuppressFinalize. Below is the sample code of the pattern. This is the
best way we do clean our unallocated resources and yes not to forget we do not get the hit
of running the Garbage collector twice.
Note:- It will suppress the finalize method thus avoiding the two trip.
Public Class ClsTesting
Implements IDisposable
Public Overloads Sub Dispose()Implements IDisposable.Dispose
' write ytour clean up code here
End Sub
Protected Overrides Sub Finalize()
End Sub
End Class
(I)In what instances you will declare a constructor to be
When we create a private constructor, we can not create object of the class directly from
a client. So you will use private constructors when you do not want instances of the class
to be created by any external client. Example UTILITY functions in project will have no
instance and be used with out creating instance, as creating instances of the class would
be waste of memory.
(I)Can we have different access modifiers on get/set
methods of a property ?
No we can not have different modifiers same property. The access modifier on a property
applies to both its get and set accessors.
(I)If we write a goto or a return statement in try and catch
block will the finally block execute ?
The code in the finally always runs even if there are statements like goto or a return
(A)What is Indexer ?
An indexer is a member that enables an object to be indexed in the same way as an array.
(A)Can we have static indexer in C# ?
(A)In a program there are multiple catch blocks so can it
happen that two catch blocks are executed ?
No once the proper catch section is executed the control goes to finally block.So there
will not be any scenarios in which multiple catch blocks will be executed.
(A) What is the difference between System.String and
System.StringBuilder classes?
System.String is immutable; System.StringBuilder can have mutable string where a variety
of operations can be performed.

Interview Questions C# and C#.Net) Set I

Interview Questions C# and C#.Net)

1. What’s the implicit name of the parameter that gets passed into the class’ set method? Value, and its datatype depends on whatever variable we’re changing.
2. How do you inherit from a class in C#? Place a colon and then the name of the base class. Notice that it’s double colon in C++.
3. Does C# support multiple inheritance? No, use interfaces instead.
4. When you inherit a protected class-level variable, who is it available to? Classes in the same namespace.
5. Are private class-level variables inherited? Yes, but they are not accessible, so looking at it you can honestly say that they are not inherited. But they are.
6. 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).
7. 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.
8. What’s the top .NET class that everything is derived from? System.Object.
9. 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.
10. What does the keyword virtual mean in the method definition? The method can be over-ridden.
11. 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.
12. 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.
13. 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.
14. 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.
15. 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.
16. 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.
17. What’s an interface class? It’s an abstract class with public abstract methods all of which must be implemented in the inherited classes.
18. 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.
19. Can you inherit multiple interfaces? Yes, why not.
20. 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.
21. 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.
22. How can you overload a method? Different parameter data types, different number of parameters, different order of parameters.
23. 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.
24. 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.
25. What’s the advantage of using System.Text.StringBuilder over System.String? StringBuilder is more efficient in the cases, where a lot of manipulation is done to the text. Strings are immutable, so each time it’s being operated on, a new instance is created.
26. Can you store multiple data types in System.Array? No.
27. What’s the difference between the System.Array.CopyTo() and System.Array.Clone()? The first one performs a deep copy of the array, the second one is shallow.
28. How can you sort the elements of the array in descending order? By calling Sort() and then Reverse() methods.
29. What’s the .NET datatype that allows the retrieval of data by a unique key? HashTable.
30. What’s class SortedList underneath? A sorted HashTable.
31. Will finally block get executed if the exception had not occurred? Yes.
32. What’s the C# equivalent of C++ catch (…), which was a catch-all statement for any possible exception? A catch block that catches the exception of type System.Exception. You can also omit the parameter data type in this case and just write catch {}.
33. Can multiple catch blocks be executed? No, once the proper catch code fires off, the control is transferred to the finally block (if there are any), and then whatever follows the finally block.
34. 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.
35. What’s a delegate? A delegate object encapsulates a reference to a method. In C++ they were referred to as function pointers.
36. What’s a multicast delegate? It’s a delegate that points to and eventually fires off several methods.
37. How’s the DLL Hell problem solved in .NET? Assembly versioning allows the application to specify not only the library it needs to run (which was available under Win32), but also the version of the assembly.
38. What are the ways to deploy an assembly? An MSI installer, a CAB archive, and XCOPY command.
39. What’s a satellite assembly? When you write a multilingual or multi-cultural application in .NET, and want to distribute the core application separately from the localized modules, the localized assemblies that modify the core application are called satellite assemblies.
40. What namespaces are necessary to create a localized application? System.Globalization, System.Resources.
41. What’s the difference between // comments, /* */ comments and /// comments? Single-line, multi-line and XML documentation comments.
42. How do you generate documentation from the C# file commented properly with a command-line compiler? Compile it with a /doc switch.
43. What’s the difference between and XML documentation tag? Single line code example and multiple-line code example.
44. Is XML case-sensitive? Yes, so and are different elements.
45. What debugging tools come with the .NET SDK? CorDBG – command-line debugger, and DbgCLR – graphic debugger. Visual Studio .NET uses the DbgCLR. To use CorDbg, you must compile the original C# file using the /debug switch.
46. What does the This window show in the debugger? It points to the object that’s pointed to by this reference. Object’s instance data is shown.
47. What does assert() do? In debug compilation, assert takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false. The program proceeds without any interruption if the condition is true.
48. 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.
49. Why are there five tracing levels in System.Diagnostics.TraceSwitcher? The tracing dumps can be quite verbose and for some applications that are constantly running you run the risk of overloading the machine and the hard drive there. Five levels range from None to Verbose, allowing to fine-tune the tracing activities.
50. Where is the output of TextWriterTraceListener redirected? To the Console or a text file depending on the parameter passed to the constructor.
51. How do you debug an ASP.NET Web application? Attach the aspnet_wp.exe process to the DbgClr debugger.
52. What are three test cases you should go through in unit testing? Positive test cases (correct data, correct output), negative test cases (broken or missing data, proper handling), exception test cases (exceptions are thrown and caught properly).
53. 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.
54. Explain the three services model (three-tier application). Presentation (UI), business (logic and underlying code) and data (from storage or other sources).
55. What are advantages and disadvantages of Microsoft-provided data provider classes in ADO.NET? SQLServer.NET data provider is high-speed and robust, but requires SQL Server license purchased from Microsoft. OLE-DB.NET is universal for accessing other sources, like Oracle, DB2, Microsoft Access and Informix, but it’s a .NET layer on top of OLE layer, so not the fastest thing in the world. ODBC.NET is a deprecated layer provided for backward compatibility to ODBC engines.
56. What’s the role of the DataReader class in ADO.NET connections? It returns a read-only dataset from the data source when the command is executed.
57. 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%’.
58. Explain ACID rule of thumb for transactions. Transaction must be Atomic (it is one unit of work and does not dependent on previous and following transactions), Consistent (data is either committed or roll back, no “in-between” case where something has been updated and something hasn’t), Isolated (no transaction sees the intermediate results of the current transaction), Durable (the values persist if the data had been committed even if the system crashes right after).
59. What connections does Microsoft SQL Server support? Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and passwords).
60. 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.
61. Why would you use untrusted verificaion? Web Services might use it, as well as non-Windows applications.
62. What does the parameter Initial Catalog define inside Connection String? The database name to connect to.
63. What’s the data provider name to connect to Access database? Microsoft.Access.
64. What does Dispose method do with the connection object? Deletes it from the memory.
65. 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.

Friday, June 13, 2008

What is the difference between VB.NET and C# ?

Well this is the most debatable issue in .NET community and people treat there languages like
religion. Its a subjective matter which language is best. Some like VB.NET’s natural style and some like professional and terse C# syntaxes. Both use the same framework and speed is also very much equivalents. But still let’s list down some major differences between them :-

Advantages VB.NET :-

√ Has support for optional parameters which makes COM interoperability much easy.
√ With Option Strict off late binding is supported.Legacy VB functionalities can be
used by using Microsoft.VisualBasic namespace.
√ Has the WITH construct which is not in C#.
√ The VB.NET part of Visual Studio .NET compiles your code in the background.
While this is considered an advantage for small projects, people creating very large
projects have found that the IDE slows down considerably as the project gets larger.
Advantages of C#
√ XML documentation is generated from source code but this is now been incorporated
in Whidbey.
√ Operator overloading which is not in current VB.NET but is been introduced in
√ Use of this statement makes unmanaged resource disposal simple.
√ Access to Unsafe code. This allows pointer arithmetic etc, and can improve
performance in some situations. However, it is not to be used lightly, as a lot of the
normal safety of C# is lost (as the name implies).This is the major difference that you
can access unmanaged code in C# and not in VB.NET.

* How much ever this book tries it can not match the huge variations of questions that have
been asked in.NET interviews.But note there will be variations and they will map to some
question of this book.

What are shared (VB.NET)/Static(C#) variables?

Static/Shared classes are used when a class provides functionality which is not specific to
any instance. In short if you want an object to be shared between multiple instances you
will use a static/Shared class.
Following are features of Static/Shared classes :-
√ They can not be instantiated. By default a object is created on the first method
call to that object.
√ Static/Shared classes can not be inherited.
√ Static/Shared classes can have only static members.
√ Static/Shared classes can have only static constructor.
Note :- In CD there is a folder “WindowsShared” which has a sample code for shared
variables.Below is a snippet. It has a “AddCount” function which increments a static
“intCount” variable. In form there are two buttons which creates a new object and displays
the count of the static variable. Even though the object is created and destroyed, the variable
values does not change. It retains its old value.
Public Class ClsShared
Shared intCount As Integer
Public Function AddCount() As Integer
intCount = intCount + 1
Return intCount
End Function
End Class
Public Class FrmSharedClasses
Inherits System.Windows.Forms.Form
Private Sub CmdInstance1_Click(ByVal sender As System.Object, ByVal
e As System.EventArgs) Handles CmdInstance1.Click
Dim pobjClsShared As New ClsShared()
MessageBox.Show(“The count at this moment is” &
End Sub
Private Sub CmdInstance2_Click(ByVal sender As System.Object, ByVal
e As System.EventArgs) Handles CmdInstance2.Click
Dim pobjClsShared As New ClsShared()
MessageBox.Show(“The count at this moment is” &
End Sub
End Class

What is Partial Assembly References?

Full Assembly reference: A full assembly reference includes the assembly's text name, version, culture, and public key token (if the assembly has a strong name). A full assembly reference is required if you reference any assembly that is part of the common
language runtime or any assembly located in the global assembly cache.

Partial Assembly reference: We can dynamically reference an assembly by providing only partial information, such as specifying only the assembly name. When you specify a partial assembly reference, the runtime looks for the assembly only in the application

We can make partial references to an assembly in your code one of the following ways:

-> Use a method such as System.Reflection.Assembly.Load and specify only a partial reference. The runtime checks for the assembly in the application directory.

-> Use the System.Reflection.Assembly.LoadWithPartialName method and specify only a partial reference. The runtime checks for the assembly in the application directory and in the global assembly cache

What is C#?

C# is a new programming language designed by Microsoft to work with the .NET framework.
It is describe C# as follows:

"C# is a simple, modern, object oriented, and type-safe programming language derived from C and C++. C# (pronounced “C sharp”) is firmly planted in the C and C++ family tree of languages, and will immediately be familiar to C and C++ programmers. C# aims to combine the high productivity of Visual Basic and the raw power of C++."

It resembles to Java.

How do you do object pooling in .NET ?

COM+ reduces overhead by creating object from scratch. So in COM+ when object is activated
its activated from pool and when its deactivated it’s pushed back to the pool. Object pooling is
configures by using the “ObjectPoolingAttribute” to the class.
Note:- When a class is marked with objectpooling attribute it can not be inherited.
ObjectPooling(MinPoolSize := 2, MaxPoolSize := 5, CreationTimeout := 20000)> _
Public Class testingclass
Inherits ServicedComponent
Public Sub DoWork()
' Method contents go here.
End Sub
End Class
Above is a sample code which has the “ObjectPooling” attribute defined. Below is a sample code
which uses the class.
Public Class App
Overloads Public Shared Sub Main(args() As String)
Dim xyz As New TestObjectPooling()
ServicedComponent.DisposeObject (xyz)
End Sub
End Class
Above is a sample code which uses the object pooled object. Note the DisposeObject() This
ensures its safe return to the object pool.

How many types of Transactions are there in COM + .NET ?

There are 5 transactions types that can be used with COM+. Whenever an object is registered with COM+ it has to abide either to these 5 transaction types.

Disabled: - There is no transaction. COM+ does not provide transaction support for this

Not Supported: - Component does not support transactions. Hence even if the calling component
in the hierarchy is transaction enabled this component will not participate in the transaction.

Supported: - Components with transaction type supported will be a part of the transaction if the
calling component has an active transaction.If the calling component is not transaction enabled this component will not start a new transaction.

Required: - Components with this attribute require a transaction i.e. either the calling should have a transaction in place else this component will start a new transaction.
Required New: - Components enabled with this transaction type always require a new transaction. Components with required new transaction type instantiate a new transaction for themselves every time.

How to implement DTC in .NET ?

DTC is implemented using COM+ .
Following are the steps to implement COM + in .NET :-
√ “EnterpriseService” namespace has all the classes by which we can implement DTC
in .NET. You have to add reference “EnterpriseService” namespace.
Figure :- 2.3 Add reference to EnterpriseServices.
√ You class must derive from “Serviced Component” object.
√ Then you have to define your class with the transaction attribute
(For all transaction attribute look the down question)
[ Transaction(TransactionOption.RequiresNew) ]
√ After the class level transaction type is defined.Its time to define at the method level
the AutoComplete attribute. Autocomplete attribute says that if no exception is thrown
then mark its part of the transaction as being okay. This helps cut down on the
amount of code required. If the implementation sets AutoComplete to false, or
omits it all together, then we would need to manage the transaction manually. To
manually control the transaction you will need to use the ContextUtil class and its static
members.Following is small snippet of ContextUtil: -
public void SampleFunction()
// Do something to a database
// ...
// Everything okay so far Commit the transaction
// Something went wrong Abort and Rollback the Transaction.
√ Component derived from “ServicedComponent” should be strong named as they
run under COM+.
√ Once the classes are compiled using the string name.Register the Component in COM+
services using
regsvcs c:\DllPath\TransactionComponent.dll
√ You can see that the component is registered using the COM+ explorer.

Can you explain what is DCOM ?

DCOM differs from COM in that it allows for creating objects distributed across a network, a
protocol for invoking that object’s methods, and secure access to the object. DCOM provides a
wrapper around COM, hence it is a backwards compatible extension. DCOM uses Remote
Procedural Calls (RPC) using Open Software Foundation’s Distributed Computing Environment.
These RPC are implemented over TCP/IP and named pipes. The protocol which is actually being
used is registered just prior to use, as opposed to being registered at initialization time. The reason
for this is that if a protocol is not being used, it will not be loaded.
In order to inform an object that the client is still alive, periodic pinging is used. Hence, when the
client has died and no ping has been received (to refresh it) before the expiration time, the server
object will perform some clean up tasks (including decrementing its reference count).
Since RPC across a network are typically slow (compared to processes residing on the same
machine), DCOM sends multiple requests in the same call. For example, in COM, the program
performs a QueryInterface, one interface at a time. In DCOM, multiple QueryInterfaces are all
clustered into one call.
This clustering optimization trick is also used when creating an instance of the object and serializing
it with data. Since these two operations usually occur together, DCOM allows one method which
will perform both operations in one call without waiting for an acknowledgment from the first
task before performing the second one.
Similarly, when a client pings its server object, he can do it in one call. Moreover, if there are
multiple clients sending pings to multiple servers, an optimization is made where the multiple
pings going to the same object are consolidated into just one ping. This is to cut down on the use
of precious bandwidth used only for pinging.
The client has the control to set the computer which will be responsible for the lifetime of the
object. That is to say, these objects are not created just somewhere where the system resources and
access privileges allow for it.
Call security is implemented in all four ways: authentication (to prevent false clients from
impersonating the true client), authorization (to insure that a client only does what it is authorized
to do), data integrity (to insure that data was not tampered with during transit) and data privacy (to
insure that only designated sources can read it). The security issues are handled as they are on
operating systems. The client gives the server various access privileges to access memory or disk

Can you describe IUKNOWN interface in short ?

Every COM object supports at least one interface, the IUnknown interface. All interfaces are
classes derived from the base class IUnknown. Each interface supports methods access data and
perform operations transparently to the programmer. For example, IUnknown supports three
methods, AddRef, Release(), and QueryInterface(). Suppose that pinterf is a pointer to an IUnknown.
pinterf->AddRef() increments the reference count. pinterf->Release() decrements the reference
count, deleting the object when the reference count reaches zero. pinterf->QueryInterface( IDesired,
pDesired) checks to see if the current interface (IUnknown) supports another interface, IDesired,
creates an instance (via a call to CoCreateInstance()) of the object if the reference count is zero (the
object does not yet exist), and then calls pDesired->AddRef() to increment the reference count
(where pDesired is a pointer to IDesired) and returns the pointer to the caller.

What is Reference counting in COM ?

Reference counting is a memory management technique used to count how many times an object
has a pointer referring to it. The first time it is created, the reference count is set to one. When the
last reference to the object is nulled, the reference count is set to zero and the object is deleted.
Care must be exercised to prevent a context switch from changing the reference count at the time
of deletion. In the methods that follow, the syntax is shortened to keep the scope of the discussion
brief and manageable.

When we use windows API in .NET is it managed or unmanaged code

Windows API in .NET is unmanaged code.
Note:- Even though VB6 and V C++ has gone off still many people do ask these old
questions again and again.Still there are decent old application which are working with
COM very much fine.So interviewer still asks you these questions so that those application’s
can be ported to .NET.So let’s play some old music..... By the way my favourite music is
Kishore what’s yours????

How can we make Windows API calls in .NET?

Windows API call are not COM based and are invoked through Platform Invoke Services.
Declare StringConversionType (Function | Sub) MethodName Lib "DllName" ([Args])
As Type
√ StringConversionType is for what type of conversion should take place.Either we
can specify Unicode to convert all strings to Unicode values, or Auto to convert
strings according to the .NET runtime rules.
√ MethodName is the name of the API to call.
√ DllName is the name of the DLL.
√ Args are any arguments to the API call.
√ Type is the return type of the API call.
Below is a sample code for VB.NET which uses Sleep windows API for delaying.
Public Class Form1
Declare Auto Sub Sleep Lib “kernel32.dll” (ByVal dwMilliseconds
As Long)
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
MessageBox.Show(“ start sleeping for 5000 Milli
MessageBox.Show(“ end of sleeping.....”)
End Sub
End Class
In VB.NET we use declare keyword but in C# it goes little bit different we use DLLIMPORT
Note :- We have interopservices in this and EXTERN keyword.
#region Using directives
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace CSharpCode
partial class Form1 : Form
static extern int Sleep(long dwMilliseconds);
public Form1()
private void Form1_Load(object sender, EventArgs e)
MessageBox.Show(“Starting of 5000 ms...”);
MessageBox.Show(“End of 5000 ms...”);

How can we use .NET components in COM?

Twist :- What is CCW (COM callable wrapper) ?, What caution needs to be taken in
order that .NET components is compatible with COM ?
.NET components can not be used in straight forward way with COM.You will need to create
CCW in order that COM components communicate with .NET assemblies.Following are the
different approaches to implement it :-
√ Explicitly declare interfaces..
Public Interface ICustomer
Property CustomerName() As String
Property CustomerCode() As String
Sub AddCustomer()
End Interface
Public Class Customer
Implements ICustomer
Private PstrCustomerName As String
Private PstrCustomerCode As String
Public Sub AddCustomer() Implements ICustomer.AddCustomer
‘ addin of database code can go here
Catch ex As Exception
Throw ex
End Try

End Sub
Public Property CustomerCode() As String Implements
Return PstrCustomerCode
End Get
Set(ByVal value As String)
PstrCustomerCode = value
End Set
End Property
Public Property CustomerName() As String Implements
Return PstrCustomerName
End Get
Set(ByVal value As String)
PstrCustomerName = value
End Set
End Property
Public Sub New()
End Sub
End Class
Note :- Source code of this is provided in CD in CODE folder in
The above customer class is going to be used by COM components so all the properties and
methods are declared in interface and implemented in the customer class.Customer Name.Customer
Code and AddCustomer are first declared in ICustomer and then implemented in Customer
Class.Note also the class must have a default constructor.
Note :- All source code in this book is provided in VB.NET that does not mean that
author of the book does not like C#. In fact the main programming language of author is
C#.In order to keep things small i have only used one language.But the conversion is so
seamless its of least matter.
√ The second way to create CCW using InteropServices attributes.Here interfaces are
created automatically.
Following are different type of class attributes :
None :No class interface is generated for the class.This is default setting when you do not specify
AutoDispatch :- Interface that supports IDispatch is created for the class. However, no type
information is produced.
AutoDual :- A dual interface is created for the class. Typeinfo is produced and made available in
the type library.
In below source code we have used the third attribute.
Imports System.Runtime.InteropServices
Public Class ClsCompliant
End Class
Other than class attributes defined up there are other attributes with which you can govern other
part of assembly.Example “GuidAttribute” allows you to specify the GUID,”ComVisibleAttribute
“ can be used to hide .NET types from COM etc.All attributes are not in scope of the book as
this is a interview questions book refer MSDN for more details.
√ Once .NET assembly is created using either interface or using interopservices method
we need to create a COM type library using Type library export tool.
Tlbexp (AssemblyName)
√ The final thing is registering the CCW in registry using regasm tool.
regasm AssemblyName [Options]
√ Finally refer the TLB in your COM IDE Below is figure showing VB6 IDE referencing
the DLL
Note :- DLL and TLB should be in same directory where the application is executed.