Tuesday, December 27, 2011

OOP’s Interview Question n Answers

OOP’s is a technique to think real words in terms of objects.
What is Static Method?
It is possible to declare a method as Static provided that they don't attempt to access any instance data or other instance methods.
What is Inheritance?
It provides a convenient way to reuse existing fully tested code in different context thereby saving lot of coding.
Inheritance of classes in C# is always implementation Inheritance.
What is Virtual keyword?
This keyword indicates that a member can be overridden in a child class. It can be applied to methods, properties, indexes and events.
What is a new modifier?
The new modifiers hide a member of the base class. C# supports only hide by signature.
What is Abstract Class?
Abstract class is a class that cannot be instantiated, it exists extensively for inheritance and it must be inherited. There are scenarios in which it is useful to define classes that is not intended to instantiate; because such classes normally are used as base-classes in inheritance hierarchies, we call such classes abstract classes.
Abstract classes cannot be used to instantiate objects; because abstract classes are incomplete, it may contain only definition of the properties or methods and derived classes that inherit this implements it's properties or methods.
Static, Value Types & interface doesn't support abstract modifiers. Static members cannot be abstract. Classes with abstract member must also be abstract.
What is Sealed modifiers?
Sealed types cannot be inherited & are concrete.
Sealed modifiers can also be applied to instance methods, properties, events & indexes. It can't be applied to static members.
Sealed members are allowed in sealed and non-sealed classes.

What is an Interface?
An interface is a contract & defines the requisite behavior of generalization of types.
An interface mandates a set of behavior, but not the implementation. Interface must be inherited. We can't create an instance of an interface.
An interface is an array of related function that must be implemented in derived type. Members of an interface are implicitly public & abstract.
An interface can inherit from another interface.
When to use Interface over abstract class?
Abstract Classes: Classes which cannot be instantiated. This means one cannot make a object of this class or in other way cannot create object by saying ClassAbs abs = new ClassAbs(); where ClassAbs is abstract class.
Abstract classes contains have one or more abstarct methods, ie method body only no implementation.
Interfaces: These are same as abstract classes only difference is we can only define method definition and no implementation.
When to use wot depends on various reasons. One being design choice.
One reason for using abstarct classes is we can code common
functionality and force our developer to use it. I can have a complete
class but I can still mark the class as abstract.
Developing by interface helps in object based communication.
What is pure virtual function?
When you define only function prototype in a base class without and do the complete implementation in derived class. This base class is called abstract class and client won’t able to instantiate an object using this base class.
A pure virtual function is a function that must be overridden in a derived class and need not be defined. A virtual function is declared to be "pure" using the curious "=0"
class Base {
void f1(); // not virtual
virtual void f2(); // virtual, not pure
virtual void f3() = 0; // pure virtual
Can we specify the access modifier for explicitly implemented interface method?
No, we can't specify the access modifier for the explicitly implemented interface method. By default its scope will be internal.
What is Protected access modifier in C#?
The protected keyword is a member access modifier. It can only be used in a declaring a function or method not in the class ie. a class can't be declared as protected class.
A protected member is accessible from within the class in which it is declared, and from within any class derived from the class that declare this member. In other words access is limited to within the class definition and any class that inherits from the class
A protected member of a base class is accessible in a derived class only if the access takes place through the derived class type.
What is Public access modifier in C#?
The public keyword is an access modifier for types and type members ie. we can declare a class or its member (functions or methods) as Public. There are no restrictions on accessing public members.
What is Private access modifier in C#?
The private keyword is a member access modifier ie. we can't explicitly declare a class as Private, however if do not specify any access modifier to the class, its scope will be assumed as Private. Private access is the least permissive access level of all access modifiers.
Private members are accessible only within the body of the class or the struct in which they are declared. This is the default access modifier for the class declaration.
What is Internal access modifier in C#?
The internal keyword is an access modifier for types and type members ie. we can declare a class as internal or its member as internal. Internal members are accessible only within files in the same assembly (.dll). In other words, access is limited exclusively to classes defined within the current project assembly.

What is Protected Internal access modifier in C#?
Protected Internal is a access modifiers for the members (methods or functions) ie. you can't declare a class as protected internal explicitly. The members access is limited to the current assembly or types derived from the containing class.
Protected Internal means the method is accessible by anything that can access the protected method UNION with anything that can access the internal method.
Default Access modifiers in C#?
An enum has default modifier as public
A class has default modifiers as Internal . It can declare members (methods etc) with following access modifiers:
protected internal
An interface has default modifier as public
A struct has default modifier as Internal and it can declare its members (methods etc) with following access modifiers:
A methods, fields, and properties has default access modifier as "Private" if no modifier is specified.
What is method overloading?
Posted by: Raja
Method overloading allows us to write different version of the same method in a class or derived class. Compiler automatically select the most appropriate method based on the parameter supplied.
public class MultiplyNumbers
{    public int Multiply(int a, int b)
    {        return a * b;    }
    public int Multiply(int a, int b, int c)    {
        return a*b*c;    }     }
To call the above method, you can use following code.
MultiplyNumbers mn = new MultiplyNumbers();
int number = mn.Multiply(2, 3) // result = 6
int number1 = mn.Multiply(2, 3, 4) // result = 24
You can't have a overload method with same number parameters but different return type. In order to create overload method, the return type must be the same and parameter type must be different or different in numbers.
What is Overriding?
Method overriding is a feature that allows to invoke functions (that have the same signatures) and that belong to different classes in the same hierarchy of inheritance using the base class reference. In C# it is done using keywords virtual and overrides .
What is Method overloading?
Method overloading occurs when a class contains two methods with the same name, but different signatures.
What is Method Overriding? How to override a function in C#?
Use the override modifier to modify a method, a property, an indexer, or an event. An override method provides a new implementation of a member inherited from a base class. The method overridden by an override declaration is known as the overridden base method. The overridden base method must have the same signature as the override method.
You cannot override a non-virtual or static method. The overridden base method must be virtual, abstract, or override.
Can we call a base class method without creating instance?
* Its possible If its a static method.
* Its possible by inheriting from that class also.
* Its possible from derived classes using base keyword.

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.
Difference between new and override keyword?
Let me explain this through code.
using System;
using System.Data;
using System.Text;
using System.Windows.Forms;
namespace BaseDerive{
    public partial class Form1 : Form    {
        public Form1()        {
            InitializeComponent();        }
        private void Form1_Load(object sender, EventArgs e)        {
            BaseClass b = new BaseClass();
            DeriveClass d = new DeriveClass();
            BaseClass bd = new DeriveClass();
            //Calls Derived class function 2 as override keyword is used.
            BaseClass bd2 = new DeriveClass();

    public class BaseClass
    {        public virtual void func1()
        {            MessageBox.Show("Base Class function 1.");
        public virtual void func2()        {
            MessageBox.Show("Base Class function 2.");
  public void func3()        {
            MessageBox.Show("Base Class function 3.");        }
    public class DeriveClass : BaseClass    {
        public new void func1()
        {            MessageBox.Show("Derieve Class fuction 1 used new keyword");
        public override void func2()        {
            MessageBox.Show("Derieve Class fuction 2 used override keyword");
public void func3()
        {            MessageBox.Show("Derieve Class fuction 3 used override keyword");
        }    }
This is a window application so all the code for calling the function through objects is written in Form_Load event.
As seen in above code, I have declared 2 classes. One works as a Base class and second is a derieve class derived from base class.
Now the difference is

new: hides the base class function.
Override: overrides the base class function.
BaseClass objB = new DeriveClass();
If we create object like above notation and make a call to any function which exists in base class and derive class both, then it will always make a call to function of base class. If we have overidden the method in derive class then it wlll call the derive class function.
For example…
objB.func1(); //Calls the base class function. (In case of new keyword)
objB.func2(); //Calls the derive class function. (Override)
objB.func3(); //Calls the base class function.(Same prototype in both the class.)
// This will throw a compile time error. (Casting is required.)
DeriveClass objB = new BaseClass();
//This will throw run time error. (Unable to cast)
DeriveClass objB = (DeriveClass) new BaseClass();
What is a private constructor? Where will you use it?
When you declare a Constructor with Private access modifier then it is called Private Constructor. We can use the private constructor in singleton pattern.
If you declare a Constructor as private then it doesn’t allow to create object for its derived class, i.e you loose inherent facility for that class.
Class A{// some code
 Private Void A() { //Private Constructor }

Class B:A{//code}
B obj = new B();// will give Compilation Error
Because Class A constructor declared as private hence its accessibility limit is to that class only, Class B can't access. When we create an object for Class B that constructor will call constructor A but class B have no rights to access the Class A constructor hence we will get compilation error.
Can we declare private class in a Namespace?
No. If you try to create a private class in a Namespace, Compiler will throw a compile time error “Namespace elements cannot be explicitly declared as private, protected, or protected internal”.
Reason: The message says it all. Classes can only be declared as private, protected or protected internal when declared as nested classes, other than that, it doesn't make sense to declare a class with a visibility that makes it unusable, even in the same module. Top level classes cannot be private, they are "internal" by default, and you can just make them public to make them visible from outside your DLL.
What is Polymorphism?
In OPP’S, polymorphism(Greek meaning “having multiple forms”) is the ablity of being able to assign a different meaning or usage to something in different contexts - specifically, to allow an entity such as a a function, or an object to have more than one forms.
In C# :
Parent classes may define and implement “virtual” methods(Which is done using the “virtual” keyword), and derived classes can override them(using the “override” keyword), which means they provide their own definition and implementation.At run-time, when user’s code calls the method, the CLR looks up the run-time type of the object, and invokes that override of the virtual method. Thus in your source code when a method of the base class is called it executes the overriden method.
What Are Attributes in DotNet?
An Attribute is a declarative tag which can be used to provide information to the compiler about the behaviour of the C# elements such as classes and assemblies.
C# provides convenient technique that will handle tasks such as performing compile time operations , changing the behaviour of a method at runtime or maybe even handle unmanaged code.
C# Provides many Built-in Attributes

Some Popular ones are
- Obsolete
- DllImport
- Conditional
- WebMethod
and Many more.
Members please keep on posting more responses providing more In-Built attributes.
Regards Hefin Dsouza
What can you do to make class available for inheritance but you need to prevent it's method to come in inheritance chain?
Well, Declare a class with public access specifier and mark all it's method to sealed . As anything which is declared with sealed keyword cannot be inherited.
What's the Difference between Interface and Abstract Class
Abstract Class:
Have constructors.
Not necessarily for the class inheriting it to Implement all the Methods.
Doesn't Support Multiple Inheritance.
Where everything is Opposite in the Interfaces.
What are the various types of Constructors
Public : Accessible to All
Private: Those classes in which only static members are there and you don't want there objects to be created in any class.
Static: Used for initializing only the static members of the class. These will be invoked for the very first time the class is being loaded on the memory. They cannot accept any arguments. Static Constructors cannot have any access modifiers.
Intern: implementations of the abstract class to the assembly defining the class. A class containing an internal constructor cannot be instantiated outside of the assembly (Namespace).
and External
What are Constructors?
Constructors are used for initializing the members of a class whenever an object is created with the default values for initialization.
If no constructor defined then the CLR will provide an implicit constructor which is called as Default Constructor.
A class can have any number of constructors provided they vary with the number of arguments that are passed, which is they should have different signatures.
Constructors do not return a value
Constructors can be overloaded
When to Use Abstract Classes and When Interfaces?
If you anticipate creating multiple versions of your component, create an abstract class. Abstract classes provide a simple and easy way to version your components. By updating the base class, all inheriting classes are automatically updated with the change. Interfaces, on the other hand, cannot be changed once created. If a new version of an interface is required, you must create a whole new interface.

If the functionality you are creating will be useful across a wide range of disparate objects, use an interface. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes.
If you are designing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class.
If you want to provide common, implemented functionality among all implementations of your component, use an abstract class. Abstract classes allow you to partially implement your class, whereas interfaces contain no implementation for any members.
Diversities between an abstract method & virtual method?
An Abstract method does not provide an implementation and forces overriding to the deriving class (unless the deriving class also an abstract class), where as the virtual method has an implementation and leaves an option to override it in the deriving class. Thus Virtual method has an implementation & provides the derived class with the option of overriding it. Abstract method does not provide an implementation & forces the derived class to override the method.

What is Early binding and late binding?
Calling a non-virtual method, decided at a compile time is known as early binding. Calling a virtual method (Pure Polymorphism), decided at a runtime is known as late binding.
Difference between ASP Session and ASP.NET Session?
Asp.net session supports cookie less session & it can span across multiple servers.
Illustrate Server.Transfer and Response.Redirect?
Server.Transfer, transfers the control of a web page, posting a form data, while Response.Redirect simply redirects a page to another page, it can not post a form data to another page. Server.Transfer is more efficient over the Response.Redirect, because Response.Redirect causes a round trip to server as the page is processed once again on the client and a request is made to server there after.
But the browser url is not changed in case of Server.Transfer i.e. Browser history is not modified in using it.
How's method overriding different from overloading?
 When overriding, you change the method behavior for a derived class. Overloading simply involves having a method with the same name within the class.
What does the keyword virtual mean in the method definition?
The method can be over-ridden.
Can you declare the override method static while the original method is non-static?
No, you can't, the signature of the virtual method must remain the same, only the keyword virtual is changed to keyword override.
Can you override private virtual methods?
No, you cannot access private methods in inherited classes.
Can you prevent your class from being inherited and becoming a base class for some other classes?
Yes, that's what keyword sealed in the class definition is for. The developer trying to derive from your class will get a message: cannot inherit from Sealed class WhateverBaseClassName. It's the same concept as final class in Java.
Can you allow class to be inherited, but prevent the method from being over-ridden?
Yes, just leave the class public and make the method sealed.

Why can't you specify the accessibility modifier for methods inside the interface?
you are not allowed to specify any accessibility, it's public by default.
Static datamembers should be initialized inside the constructor. True or False.
False. Static datamembers should not be initialised inside constructor.
Static methods can not use non static members. True or False.
A constructor can be private. True or False
True. A constructor can be private. We can declare a constructor as private.
What is the work of a constructor?
 Constructor creates and initialises the objects in an application.
Name the operators that cannot be overloaded.
What is "this" pointer?
This pointer is a pointer which points to the current object of a class. this is actually a keyword which is used as a pointer which differentiate the current object with global object.
public class Base { public virtual void foo(int x) { Console.WriteLine("Base foo(int)"); } } public class Derived: Base { public void foo(int x) { Console.WriteLine("Derived foo(int)"); } } class Program { static void Main(string[] args) { Derived d = new Derived(); int i = 10; d.foo(i); } }
NOTE: This is objective type question, Please click question title for correct answer.
Difference between sealed and static classes
sealed classes:
1)we can create their instances, but cannot inherit them ex:
sealed class demo {
class abc:demo {
--Wrong }
2)They can contain static as well as nonstatic members.
static classes:
1)we can neither create their instances, nor inherit them
 static class Program { }
2)They can have static members only.
Differences between a structure and class
1)It is a Value Type
2)Its variable directly contains the data on the stack
3)Each structure variable has its independent copy
of data.
4)One structure cannot inherit other
5)They do not have destructors
6)They do no have explicit parameterless constructors
7)we cannot put sealed /abstract modifiers before the structures.
8)Easier memory management
int, short,long,DateTime,

Structures are typically used for handling
small amounts of data or where inheritance, overriding is not required
example: int a=100;
1)It is a reference Type
2)Its variable has references to the data(data is stored in the object created in the heap) .
3)Two Class variables can refer to the same object
4)One class can inherit the other(unless the class is sealed/static)
5)Classes have destructors
6)They can have explicit parameterless constructors
7)Sealed/abstract modifers can be put before classes.
8) Comparitively Difficult memory management
9)example: SqlConnection,DataView(predefined classes)
Classes are typically used where inheritance, overriding is required
or we need to create objects capable of handling large data
example: DataSet,ArrayList can handle large data.
What are the different ways a method can be overloaded?
Different parameter data types, different number of parameters, different order of
example: int area(int a, int b) {
return a*b; --different number of parameters }
int area(int b) {
return a*a; }
--parameter return types
int calc(int a) { return a; }
double calc(double b) { return b*5; }
Difference between a Class and an object
1)It is a datatype that contains the programming logic.
2)Class is visible in the source code and resides in hard disk.
3)Class is like a template or blueprint of the object. It implements reusability,
encapsulation, inheritance
example:Button is a class with properties like Text,BackColor,
events like click, methods like Focus
1)it is a chunk of memory that implements the class logic.
2)Object is in the RAM and not visible in source code.
3)It is the real world implementation of the class.
Each object has its own copy of data.
example: Button1, Button2 are the objects of Button class.
Define OOPS. What are its benefits?
Object Oriented Programming Stuctures:
It is a programming methodology in which the programs are organized as collections of objects.Each object represents an instance of some class.The classes can be interrelated to each other through inheritance

OOPS revolves around these concepts:
1)Code reusability: define a class and n number of objects implement the class
logic: example: Button class and n number of Button objects
2)Inheritance : Eliminates redundant code and extend the use of existing classes.
example: 1)we can create our own TextBox by inheriting from the TextBox class.
2)We can inherit one Windows Frorm into another.
3)Encapsulation: The programmer can hide the data and functions in a class from other classes.It is accomplished through modifiers like private, protected,
protected internal.
4)Easy to Maintain and Upgrade:
If we want to make changes in a class, we can make them and save the changes in the .dll This .dll can easily be updated in the client by using Update Reference.
5)Polymorphism provides us with methods extensibility.
we can have different methods with same name, but with different kinds of behavior

6)Abstraction allows us to define a common definition of a base class
that multiple derived classes can share.
For example,
create an abstract class bank with simple interest function
This function will be implemented in the derived classes of
the bank class.
ex: 1)icici class will have its own simple interest.
2)ABC class will have its own simple interest.
icici and ABC both are child classes of bank class.
Can we have Sealed Method in abstarct class ?
Looking at first site the The Keyword Sealed & Abstract are contradictory to each other..In simple terms we can Say Answer is NO...
Look the code below
using System;
abstract class A {
public abstract void Hello();
public sealed void Hi();
when we will complie the code.. we will get the Compile time Error as below
'A.Hi()' cannot be sealed because it is not an override..
But the Crux is We can have Sealed methods in abstract class when the abstract class is Dervided class .. for Eg.
using System;
class A { public virtual void Hello() {
Console.WriteLine(" Say Hello"); } }
 abstract class B : A {
public sealed override void Hello() {
Console.WriteLine(" Say Hi"); }
class C : B { }
class Demo {
public static void Main() {
C c1 = new C();
c1.Hello();// Output is Say Hi }
// Thanks
Can we have an Abstract class without having any abstract method ??
Yes we can have Abstract class without having any abstract method ..
See the code below
using System;
abstract class A {
public void Hello() {
Console.WriteLine(" Say Hi"); }
class B:A { }
class Demo {
public static void Main() {
B b1 = new B();
b1.Hello(); }
// Output is Say HI
the class A is abstract class.. but it does not have any abstract methods..
Can we have Multiple Main Methods in one .cs file
Yes we can Have multiple Main methods in one .cs file.
The crux is we can have Multiple classes in one .cs file; and we can define one Main method in each class.
& while doing compliation we can spcify the compiler to choose the Main methods from the specific class .
for ef see the code below
using System;
class Test{
    public static void Main()    {
class Demo{
    public static void Main()
    {        Console.WriteLine("Demo");
We have got two class which we can save in single .cs file say Hello.cs
while doing compliation we can say
csc Hello.cs /main:Demo        --> In order to choose Main from the Demo class
csc Hello.cs /main:Test      --> In order to choose Main from the Test class

Which of these terms defines the hiding of an object's details from the other program?
NOTE: This is objective type question, Please click question title for correct answer.
If the Function has same parameter but different return type (int and float), Is it a overloading?
NOTE: This is objective type question, Please click question title for correct answer.
How does Composition mechanism works ?
This mechanism helps to simplify a complex problem into an easier problem.It generally makes different classes and objects to communicate with each other and thus making the problem solved. It communicates with the problem by making different classes and objects to send a message to each other.
What is the advantage of parametric polymorphism ?
Generally in Parametric polymorphism the code is written without following any specification for the type of data present so this particular code can be used any number of times. Hence code re-usability is achieved.
When We will create architecture and show one application connect with different type of database like SQL or Oracle. Which option is suitable for create architecture?
NOTE: This is objective type question, Please click question title for correct answer.
What is difference in between abstrct classes and interfaces ?
An interface offers an alternative to an abstract class for creating contract among classes and their client. The main difference in between abstract class and interface are given bellow
1. Abstract classes can have concrete methods while interfaces have no methods implemented.
2.Interface do not come in inheriting chain,while abstract classes come in inheritance .

ripalmsoni Interview Questions for .Net 12 Comments
“The ability to define a class and create instances of classes is one of the most important capabilities of any Object Oriented Language”
Q: How will you define a CLASS ?
A: All classes in Visual Basic. NET are defined in a .VB file (as oppose to .CLS file in vb6), Also .VB file may contain one or more classes. The basic syntax of a class is as follows:

Class ClassName
End Class
Public|Protected|Friend|Protected Friend|Private Class Vehicle
End Class
Q: List All Class Access Specifiers?
A: There are five access specifiers in Visual Basic .NET defined as follows:
•             Public – Applied at the class level and is the most common specifier. Public Classes are classes that are intended to be used by any consumer.
Public Class PubClass
End Class
•             Protected – can only be applied to Nested Classes. Are only accessible within the class and within the child classes.
Public Class HasProtected
Protected Class ProtectedClass
End Class
End Class
•             Friend – Are accessible only within the program in which they are defined. If you add the Friend access specifier to a class definition, instance of that class can only be created from within th same program.
Friend Class FriendClass
Public Shared Sub PublicMethod()
End Sub
End Class
•             Protected Friend – Represents a union of the Protected and Friend Specifiers. Protected class must be nested class, thus Protected Friend class must be nested too.

Public Class HasProtectedFriend
Protected Friend Class ProtectedFriend
Public Shared Sub Test()
End Sub
End Class
End Class
•             Private – Can only be applied to a nested class. A Private nested class represents implementation details of the class. When you have complex problem that requires more problem solving horsepower then simple methods can provided, defining a nested private class that implements the abstraction.
Public Class HasPrivate
Private Class PrivateClass
End Class
End Class
Q: What is a Field?
A: Field is a Data Member of a class. Fields can be ValueType members, like Integer or Dates, or can be aggregate types, like structures or classes.

Q: What is a Property?
A: A Property is a special member constructor that is used like a field, but acts like a method. Properties are special kind of methods that generally are used to provide constrained access to Field.
Q: What are the Indexed Properties?
A: Indexed Properties are simply property methods that have a mandatory parameter. The mendatory parameter is semantically treated like an index Index properties has an argument between the parentheses. This argument doesn’t represent the field value; rather, it represents an index to an underlying field value. The fundamental idea behind indexed properties is that you can wrap arrays and other kind of collections of data safely behind property methods.

Public Class Indexed
Private FStrings() As String = {“One”, “Two”, “Three”}
Public Property Strings(ByVal index As Integer) As String
Return FStrings(index)
End Get
Set(ByVal value As String)
FStrings(index) = value
End Set
End Property
End Class
Q: Explain Default Properties?
A: Default Properties must be indexed properties, you can have only one default property per class and you can invoke property setter and getter methods on a default property using the verbos or shorthand form.
Public Class Indexed
Private FStrings() As String = {“One”, “Two”, “Three”}
Default Public Property Strings(ByVal index As Integer) As String
Return FStrings(index)
End Get
Set(ByVal value As String)
FStrings(index) = value
End Set
End Property
End Class
Q: What are ReadOnly, WriteOnly and Shared Properties?
A: Read Only property is a property that can be used as an r- value only. That’s why a property statement that includes a read only modifier will generate a getter block only and users can evaluate this property but can not modify it.
Public ReadOnly Property Strings(ByVal index As Integer) As String
Return FStrings(index)
End Get
End Property
Write Only – is a property that a consumer can modify but can’t view. This implements a property setter only.
Public WriteOnly Property Strings(ByVal index As Integer) As String
Set(ByVal value As String)
FStrings(index) = value
End Set
End Property
Shared Property – is a property that a shared members can also be invoked using instances.
Public Property Strings(ByVal index As Integer) As String
Return FStrings(index)
End Get
End Property

Q: What is Constructor and Destructor ?
A: A constructor is called to Initialize a class. A destructor is called to Finalize the class. Visual Basic.NET implements the constructor as Sub New and Destructor as protected method Sub Finalize().
Q: what is MyBase and MyClass?
A: MyBase allows you to invoke methods in your class’s Base Class that may be overloaded in your class, resolving any name ambiguity.
MyClass is roughly equivalent to the Me reference to self.
Q: what is Method Overloading?
A: Method Overloading means to have two or more methods in the same class with different signature. The benefit of method overloading is that it allows you to implement methods that supports the same semantic operation but differ by argument number or type.
Public Overloads Sub GetCustomer(ByVal strCustomerName As String)
End Sub
Public Overloads Sub GetCustomer(ByVal iCustomerID As Integer)
End Sub
Q: what is Method OverRidingd?
A: Method Overriding changing the behavior of a method in a base class. Use keyword Overrides.
Q: what are Overridable, MustOverride and NotOverridable modifiers?
A: Overridable – modifier indicates that a method can be overriden.
NotOverridable- modifier indicates that you can not override a method.
MustOverride- modifier indicates that a method is abstract, and child class must implement the MustOverride method in a parent class.
Q: what Shadows modifier?
A: Shadows – if you want a child class to use a name previously used in a parent class, use the Shadows keyword to do so. Shadows keyword simply allows you to reintroduce a previously used name in the child class without a compiler error.

1.            List few features of object oriented programming.Object oriented programming features:
Follows bottom up approach.
Emphasis is on data.
Programs are divided into objects.
Functions and data are bound together.
Communication is done through objects.
Data is hidden.
2. List features of procedure oriented programming.Procedure oriented programming features:
Follows top down approach.
Emphasis is on procedure.
Programs are divided into functions.
Data moves around freely.
3. What are the basic concepts of OOPs?The following are the basic concepts of OOPs:
Classes, Objects, Data abstraction and encapsulation, Polymorphism, Inheritance, Message Passing, and Dynamic Binding.
4. What is a class?
Class is an entity which consists of member data and member functions which operate on the member data bound together.
5. What is an object?
Objects are instances of classes. Class is a collection of similar kind of objects. When a class is created it doesn’t occupy any memory, but when instances of class is created i.e., when objects are created they occupy memory space.
6. What is data encapsulation?
Wrapping up of member data and member functions together in a class is called data encapsulation.
7. What is data abstraction?
Data abstraction refers to the act of providing only required features and hiding all the non-essential details for usage.
8. What are ADTs?
ADTs stand for abstract data types. Classes which provide data abstraction are referred to as ADTs.
9. What is inheritance?
The process of inheriting the properties of one object by another object is called inheritance.
10. What is polymorphism?
The feature of exhibiting many forms is called polymorphism.
11. What are the steps involved in message passing?The following are the steps involved in message passing:
Creating classes, creating objects, and creating communication between objects.
12. What is dynamic binding?
The feature that the associated code of a given function is not known till run time is called dynamic binding.
13. What are the advantages of OOP?Data hiding helps create secure programs.
Redundant code can be avoided by using inheritance.
Multiple instances of objects can be created.
Work can be divided easily based on objects.
Inheritance helps to save time and cost.
Easy upgrading of systems is possible using object oriented systems.
14. Give an example for object based programming language.
Ada is an example for object based programming language.
15. Write the features of object based programming language.
Data hiding, data encapsulation, operator overloading and automatic initialization and clear up of objects are the important features exhibited by object based programming languages.
.Net Interview Questions and Answers on OOPS
Frequently asked .Net Interview Questions and Answers on Object Oriented Programming (OOPS)
.NET Interview Questions and answers on OOPS

What is an Object in OOPS??
An object is a software bundle of variables and related methods. Objects are related to real life scenario. Class is the general thing and object is the specialization of general thingObjects is instance of classes.
Declaration of an Object in OOPs
ClassName objectName=new ClassName();
E.g.: Person objPerson= new Person();
An object is characterized by concepts like:
•             Attribute
•             Behavior
•             Identity
What is an Attribute in OOPs??
•             Attributes define the characteristics of a class.
•             The set of values of an attribute of a particular object is called its state.
•             In Class Program attribute can be a string or it can be a integer.
What is Encapsulation in OOPS??
•             Encapsulation is one of the fundamental principles of object-oriented programming.
•             Encapsulation is a process of hiding all the internal details of an object from the outside world.
•             Encapsulation is the ability to hide its data and methods from outside the world and only expose data and methods that are required
•             Encapsulation is a protective barrier that prevents the code and data being randomly accessed by other code or by outside the class
•             Encapsulation gives us maintainability, flexibility and extensibility to our code.
•             Encapsulation makes implementation inaccessible to other parts of the program and protect from whatever actions might be taken outside the function or class.
•             Encapsulation provides a way to protect data from accidental corruption
•             Encapsulation hides information within an object
•             Encapsulation is the technique or process of making the fields in a class private and providing access to the fields using public methods
•             Encapsulation gives you the ability to validate the values before the object user change or obtain the value
•             Encapsulation allows us to create a "black box" and protects an objects internal state from corruption by its clients.
There are two ways to create a validation process.
•             Using Assessors and Mutators
•             Using properties
Benefits of Encapsulation
•             In Encapsulation fields of a class can be read-only or can be write-only
•             A class can have control over in its fields
•             A class can change data type of its fields anytime but users of this class do not need to change any code
What is Inheritance in OOPS? 
•             Inheritance, together with encapsulation and polymorphism, is one of the three primary characteristics (concept) of object-oriented programming
•             Inheritance enables you to create new classes that reuse, extend, and modify the behavior that is defined in other classes
•             The Class whose methods and variables are defined is called super class or base class
•             The Class that inherits methods and variables are defined is called sub class or derived class
•             Sometimes base class known as generalized class and derived class known as specialized class
•             Keyword to declare inheritance is “:” (colon) in visual c#
Benefits of using Inheritance
•             Once a behavior (method) or property is defined in a super class(base class),that behavior or property is automatically inherited by all subclasses (derived class).
•             Code reusability increased through inheritance
•             Inheritance provide a clear model structure which is easy to understand without much complexity
•             Using inheritance, classes become grouped together in a hierarchical tree structure
•             Code are easy to manage and divided into parent and child classes
When we define clean up destructor , how does it affect garbage collector?
If you define clean up in destructor garbage collector will take more time to clean up the objects and more and more objects are created in Gen 2..
What is Polymorphism in OOPS?
•             Polymorphism is one of the primary characteristics (concept) of object-oriented programming
•             Poly means many and morph means form. Thus, polymorphism refers to being able to use many forms of a type without regard to the details
•             Polymorphism is the characteristic of being able to assign a different meaning specifically, to allow an entity such as a variable, a function, or an object to have more than one form
•             Polymorphism is the ability to process objects differently depending on their data types
•             Polymorphism is the ability to redefine methods for derived classes.
Types of Polymorphism
Compile time Polymorphism
•             Run time Polymorphism
What is Access Modifier in OOPS?
Access modifiers determine the extent to which a variable or method can be accessed from another class or object.
•             Private
•             Protected
•             Internal
•             Protected Internal
•             Public

1. Give some examples of pure object oriented languages.
Eiffel, Java, Simula, Smalltalk are some pure object oriented languages.
2. List the areas of applications of object oriented programming?The following are few areas of applications of object oriented programming:
CAD/CAM systems
Office automation and decision support systems
Object oriented databases
Real time systems
Simulation and modelling.
3. What is the difference between structure in C and class in C++?
In C structure, by default the members are public. Whereas in C++ class, by default the members are private.
4. What are the sections in class specification?
There are basically two sections in class specification: Class declaration and class function definition.
5. Write the syntax for class declaration.
class {

6. What are class members?
The variables and functions used in a class are called class members.
7. What are the visibility labels?
Private, public and protected are the visibility labels.
8. Give an example for class declaration.
class area{
int r;
void get(int r);
void area(int r);
9. How does a class provide data hiding?
Data hiding is provided by a class by the use of visibility label private which allows only the member functions to access the data declared as private.
10. What are the ways of defining member functions?
Member functions can be defined in two ways, one inside the class definition and the other outside the class definition.
11. Write the syntax for defining member functions inside the class.Syntax:
class {
return type {
12. Write the syntax for defining member functions outside the class.Syntax:
return type :: (arguments){
13. What does member functions represent?
Member functions of a class represent the behaviour of a class.
14. Write the syntax for making an outside function inline?Member functions can be made inline even though we define them outside the class by using the keyword inline.
class {
return type (arguments);};
inline return type :: (arguments){
15. What is an object?
A region of storage with associated semantics is called an object.
1) What is meant by Object Oriented Programming?
     OOP is a method of programming in which programs are organised as cooperative collections of objects. Each object is an instance of a class and each class belong to a hierarchy.
2) What is a Class?
     Class is a template for a set of objects that share a common structure and a common behaviour.
3) What is an Object?
     Object is an instance of a class. It has state,behaviour and identity. It is also called as an instance of a class.
4) What is an Instance?
     An instance has state, behaviour and identity. The structure and behaviour of similar classes are defined in their common class. An instance is also called as an object.
5) What are the core OOP’s concepts?
     Abstraction, Encapsulation,Inheritance and Polymorphism are the core OOP’s concepts.
6) What is meant by abstraction?
     Abstraction defines the essential characteristics of an object that distinguish it from all other kinds of objects. Abstraction provides crisply-defined conceptual boundaries relative to the perspective of the viewer. Its the process of focussing on the essential characteristics of an object. Abstraction is one of the fundamental elements of the object model.
7) What is meant by Encapsulation?
     Encapsulation is the process of compartmentalising the elements of an abtraction that defines the structure and behaviour. Encapsulation helps to separate the contractual interface of an abstraction and implementation.
 What is meant by Inheritance?
     Inheritance is a relationship among classes, wherein one class shares the structure or behaviour defined in another class. This is called Single Inheritance. If a class shares the structure or behaviour from multiple classes, then it is called Multiple Inheritance. Inheritance defines “is-a” hierarchy among classes in which one subclass inherits from one or more generalised superclasses.
9) What is meant by Polymorphism?
     Polymorphism literally means taking more than one form. Polymorphism is a characteristic of being able to assign a different behavior or value in a subclass, to something that was declared in a parent class.
10) What is an Abstract Class?
     Abstract class is a class that has no instances. An abstract class is written with the expectation that its concrete subclasses will add to its structure and behaviour, typically by implementing its abstract operations.
11) What is an Interface?
     Interface is an outside view of a class or object which emphaizes its abstraction while hiding its structure and secrets of its behaviour.
12) What is a base class?
     Base class is the most generalised class in a class structure. Most applications have such root classes. In Java, Object is the base class for all classes.
13) What is a subclass?
     Subclass is a class that inherits from one or more classes
14) What is a superclass?
     superclass is a class from which another class inherits.
15) What is a constructor?
     Constructor is an operation that creates an object and/or initialises its state.
16) What is a destructor?
     Destructor is an operation that frees the state of an object and/or destroys the object itself. In Java, there is no concept of destructors. Its taken care by the JVM.
17) What is meant by Binding?
     Binding denotes association of a name with a class.
18) What is meant by static binding?
     Static binding is a binding in which the class association is made during compile time. This is also called as Early binding.
19) What is meant by Dynamic binding?
     Dynamic binding is a binding in which the class association is not made until the object is created at execution time. It is also called as Late binding.
20) Define Modularity?
     Modularity is the property of a system that has been decomposed into a set of cohesive and loosely coupled modules.
21) What is meant by Persistence?
     Persistence is the property of an object by which its existence transcends space and time.
22) What is colloboration?
     Colloboration is a process whereby several objects cooperate to provide some higher level behaviour.
23) In Java, How to make an object completely encapsulated?
     All the instance variables should be declared as private and public getter and setter methods should be provided for accessing the instance variables.

24) How is polymorphism acheived in java?
     Inheritance, Overloading and Overriding are used to acheive Polymorphism in java.
What is Object Oriented Programming?
It is a problem solving technique to develop software systems. It is 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.
What’s a Class?
A class describes all the attributes of objects, as well as the methods that implement the behavior of member objects. It’s a comprehensive data type which represents a blue print of objects. It’s a template of object.
What’s an Object?
It is 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.
What is 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.
What is Abstraction?
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.
What is Encapsulation?
It is a process of hiding all the internal details of an object from the outside world.
What is Object lifetime?
All objects have life time.Objects are created ,and 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.

What is Association?
This is the simplest relationship between objects. Example every customer has sales. So Customer object and sales object have an association relation between them.
What is Aggregation?
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.
What is Polymorphism?
When inheritance is used to extend a generalized class to a more specialized class, it includes behavior of the top class(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.
What are abstract classes?
Following are features of a abstract class :-
1. You can not create a object of abstract class.
2. 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.
3. Abstract classes are similar to interfaces. After declaring an abstract class, it cannot be instantiated on its own, it must be inherited.
4. In VB.NET abstract classes are created using “MustInherit” keyword.In C# we have “Abstract” keyword.
5. Abstract classes can have implementation or pure abstract methods which should be implemented in the child class.
What is a Interface?
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 know 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.

What is difference between abstract classes and interfaces?
Following are the differences between abstract and interfaces :-
1. Abstract classes can have concrete methods while interfaces have no methods implemented.
2. Interfaces do not come in inheriting chain, while abstract classes come in inheritance.
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.
 Do events have return type?
No, events do not have return type.
 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 class.
Can we have shared events?
Yes, you can have shared event’s. Note: Only shared methods can raise shared events.
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.
What is the difference between Shadowing and Overriding?
Following are the differences between shadowing and overriding :-
1. Overriding redefines only the implementation while shadowing redefines the whole element.
2. In overriding derived classes can refer the parent class element by using “ME” keyword, but in shadowing you can access it by “MYBASE”
What is the 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. 212 Just imagine one of your clients doing this c.XyzCallback = null This will reset all your delegates to nothing and you have to keep searching where the error is.
If we inherit a class do the private variables also get inherited?
Yes, the variables are inherited but cannot be accessed directly by the class interface
What are the different accessibility levels defined in .NET?
Following are the five levels of access modifiers :-
1. Private : Only members of class have access.
2. Protected :-All members in current class and in derived classes can access the variables.
3. Friend (internal in C#) :- Only members in current project have access to the elements.
4. Protected friend (protected internal in C#) :- All members in current project and all members in derived class can access the variables.
5. Public :- All members have access in all classes and projects.
Can you prevent a class from overriding?
If you define a class as “Sealed” in C# and “NotInheritable” in VB.NET you cannot inherit the class any further.
What is 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.You can not create an object of a class which is marked as “MustInherit”. When you define “MustInherit” keyword for class you can only use the class by inheriting.
Do interface have accessibility modifier?
All elements in Interface should be public. So by default all interface elements are public by default.
What are similarities between Class and structure?
Following are the similarities between classes and structures :-
1. Both can have constructors, methods, properties, fields, constants, enumerations, events, and event handlers.
2. Structures and classes can implement interface.
3. Both of them can have constructors with and without parameter
4. Both can have delegates and events.
What is the difference between Class and structure’s?
Following are the key differences between them :-
1.Structure are value types and classes are reference types. So structures use stack and classes use heap.
2. Structures members can not be declared as protected, but class members can be. You can not do inheritance in structures.
3. Structures do not require constructors while classes require.
4.Objects created from classes are terminated using Garbage collector. Structures are not destroyed using GC.
What does virtual keyword mean?
They are that method and property can be overridden.
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 :-
1. They can not be instantiated. By default a object is created on the first method call to that object.
2. Static/Shared classes can not be inherited.
3. Static/Shared classes can have only static members.
4. Static/Shared classes can have only static constructor.
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.
What is 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
Where are all .NET Collection classes located?
System.Collection namespace has all the collection classes available in .NET.

What is ArrayList?
Array is whose size can increase and decrease dynamically. Array list can hold item of different types. As Array list 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 position.
What’s a HashTable?
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.
What are queues and stacks?
Queue is for first-in, first-out (FIFO) structures. Stack is for last-in, first-out (LIFO) structures.
What is ENUM?
It’s used to define constants.
What is Operator Overloading in .NET?
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
What is 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 218 which can be overridden and clean up code for unmanaged resources can be put in this section.
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 overridden. Now when garbage collector runs for the first time it searches for objects whose memory has to free. He can see 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 released and then checks for the finalization queue and at this moment it clears object2 from the memory. So if you notice that object2 was released 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.
How can we suppress a finalize method?
GC.SuppressFinalize ()
What is 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 220 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.
How do I force the Dispose method to be called automatically, as clients can forget to call Dispose method?
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 GC.SuppressFinalize(Me) End Sub Protected Overrides Sub Finalize() Dispose() End Sub End Class
In what instances you will declare a constructor to be private?
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 221 instance and be used with out creating instance, as creating instances of the class would be waste of memory.
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.
Can we write a goto or a return statement in try and catch block will the finally block execute?
The code in then finally always run even if there are statements like goto or a return statements.
What is Indexer?
An indexer is a member that enables an object to be indexed in the same way as an array.

Can we have static indexer in C#?
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 finally to block. So there will not be any scenarios in which multiple catch blocks will be executed.
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.

What is Polymorphism?
Polymorphism means same operation may behave differently on different classes.
Example of Compile Time Polymorphism: Method Overloading
Example of 
Run Time Polymorphism: Method Overriding

Example of Compile Time Polymorphism

Method Overloading
- Method with same name but with different arguments is called method overloading.
- Method Overloading forms compile-time polymorphism.
- Example of Method Overloading:
class A1
void hello()
{ Console.WriteLine(“Hello”); }

void hello(string s)
{ Console.WriteLine(“Hello {0}”,s); }

Example of Run Time Polymorphism

Method Overriding
- Method overriding occurs when child class declares a method that has the same type arguments as a method declared by one of its superclass.
- Method overriding forms Run-time polymorphism.
- Note: By default functions are not virtual in C# and so you need to write “virtual” explicitly. While by default in Java each function are virtual.
- Example of Method Overriding:
Class parent
virtual void hello()
{ Console.WriteLine(“Hello from Parent”); }

Class child : parent
override void hello()
{ Console.WriteLine(“Hello from Child”); }

static void main()
parent objParent = new child();
Hello from Child.

No comments: