OOPS Interview Questions in .NET

We have compiled most frequently asked .NET Interview Questions which will help you with different expertise levels.

.NET Interview Questions on OOPS

Note: We have come out with a exclusive book on ‘OOP’s with real project scenarios’. In this book 
          we have tried to understand OOP’s fundamentals and also tried to apply them on projects by 
          simulating project scenarios.

Question 1.
What Is Object-Oriented Programming?
Answer:
OOP is a software designing technique where we think in terms of real-world objects.

Question 2.
What are a class and object?
Answer:
Class is a blueprint/template. Objects are instances of classes, in other words, they bring life in class. To use a class we need to ideate an object.

Question 3.
What are different properties provided by object-oriented systems?
Answer:
Following are characteristics of an object-oriented system:

Abstraction: Abstraction means show only what is necessary. Example color is abstracted to RGB (Red, Green Blue). By just making the combination of these three colors we can achieve any color in the world. So rather than remembering each and every color we just use RGB.

Encapsulation: It is a process of hiding all the complex processing from the outside world and makes your objects simple.

Inheritance: This concept helps to define the parent-child relationship between classes.

Polymorphism: It is a property of an object to act differently under different conditions. For instance, a simple user object depending on conditions can act as an admin or as a data entry object.
Remember the word APIE (Abstraction, Polymorphism, Inheritance, and Encapsulation).

Question 4.
How can we implement encapsulation in .NET?
Answer:
Encapsulation can be achieved by using the below five access modifiers.

  • Private: Only members of the class have access to the variables.
  • Protected: All members in the current class and in derived classes can access the variables.
  • Friend (internal in C#): Only members in the current project have access to the elements.
  • Protected friend (protected internal in C#): All members in the current project and all members in the derived class can access the variables.
  • Public: All members have access to all classes and projects.
Note: This question can also be tweaked by asking what are the different access modifiers in .NET

Question 5.
What’s the difference between abstraction and encapsulation?
Answer:

Note:  This question is a bit confusing question. Abstraction says show only what is necessary 
         and encapsulation says hide complexity. Does it look like talking the same things with different faces?

Abstraction and encapsulation complement each other. Encapsulation implements abstraction. Abstraction is the design process while encapsulation happens during the coding phase which is achieved by using access modifiers. Abstraction is done in the design phase while encapsulation is implemented in the execution phase using access modifiers.

Question 6.
How is inheritance implemented in .NET?
Inheritance is implemented by using the “:” symbol.
Below is a simple code snippet where we have the “Customer” class which is the parent class. We have then created a child class called “CustomerDiscount” which inherits all the properties and adds a “Discount” property.

class Customer
{
       public string customer name;
       public string customer code;
}
class CustomerDiscount: Customer
{
       public double Discount;
}

Question 7.
What are the two different types of polymorphism?
Answer:
There are two kinds of polymorphism static and dynamic. Many people also call them runtime or compile-time polymorphism.

Question 8.
How can we implement static polymorphism?
Answer:
Static polymorphism is implemented by using method overloading. In compile-time itself, we come to know if there are mismatches. The below code snippet shows how method overloading is implemented. The add method can take either 2 inputs or 3 inputs.
Depending on the number of inputs the addition logic is executed.

// add method with 2 inputs,
objmaths.add(1, 2);
// add method with 3 inputs,
objmaths.add(1, 2, 3);

Question 9.
How can we implement dynamic polymorphism?
Answer:
Dynamic polymorphism is implemented by using override and virtual keywords.
Below is a simple code snippet that has three classes, Customer class is the parent class.
CustomerDiscountlOPercent and CustomerDiscount2OPercent are child classes.
Customer parent class has a discount function which returns zero discounts. This function is defined as virtual and then overridden by both the child classes with 10% and 20% discounts.

class Customer
{
      public string customerName;
      public string customerCode;
      public virtual int Discount( )
      {
            return 0;
      }
}
class CustomerDiscountlOPercent: Customer
{
      public override int Dis.count( )
      {
          return 10;
      }
}
class CustomerDiscount20Percent: Customer
{
      public override int Discount()
      {
          return 20;
      }
}

Now on the client-side on the fly, your parent object can point to any child classes and invoke the child implementation accordingly. This is called dynamic polymorphism; the parent object can point to any of the child objects and invoke the child function dynamically.

Customer obj;
obj = new CustomerDiscountlOPercent();
obj = new CustomerDiscount2OPercent();

Question 10.
What are downcasting and upcasting?
Answer:
“Upcasting” means moving subclass objects to the parent class object. “Downcasting” is opposite to “Upcasting” moving the parent object to the child object.

OOP Interview Questions in . NET chapter 3 img 1

“Upcasting” is perfectly valid but “Downcasting” is not allowed in .NET as shown in Figure 3.1. For instance below is a simple “Customer” parent class which is further inherited by a child class “GoldCustomer”.

class Customer
{
}
class GoldCustomer: Customer
{
}

Below is an “upcasting” code where the child-parent class GoldCustomer is pushed to the Customer class.

Customer obj=new GoldCustomer( );

Below is a sample of “downcasting” code where a parent class object is tried to move to a child class object, this is not allowed in .NET.

GoldCustomer obj = new Customer( ); //not allowed illegal

Question 11.
What is the difference between overriding and overloading?
Answer:

Note:  I am not sure why this question is asked frequently. It’s like comparing apples with mangoes. 
          Probably it’s just the common word “over” which confuses developers.

Overloading is a concept where we can have the same method names with different input signatures. In overriding, we have a parent class with virtual functions which are overridden in the child classes.

Question 12.
What is operator overloading?
Answer:
Operator overloading is a concept of polymorphism where you can redefine operators like +, *, etc.,
with additional functionalities.

For instance, we can redefine the + functionalities to add objects like obj l + obj 2. Below is the simple code snippet which redefines the + operator.

class SomeClass
{
      private int someValue;
      public SomeClass(int val)
      {
            someValue = val;
      }
      public static SomeClass operator +(SomeClass argl, SomeClass arg2)
      {
            return new SomeClass(arg1.someValue + arg2.someValue);
      }
}

You can now use the + operator to add objects of type some class as shown in the below code snippet.

Obj = obj1 + obj2;

Question 13.
What are abstract classes?
Answer:
An abstract class is a half-defined parent class. The full implementation of abstract class is defined by the child classes.
For example below code, snippet shows a simple abstract class/half-defined class called “DatabaseCommon” and later the concrete classes, i.e., “SQLServer” and “Oracle” inherit and define a complete implementation for the same. To define an abstract class we need to use the abstract keyword.

public abstract class DatabaseCommon
{
}
public class SQLServer: DatabaseCommon
{
}
public class Oracle: DatabaseCommon
{
}

Question 14.
What are abstract methods?
Answer:
Abstract classes can have abstract methods. Abstract methods when defined in a parent class have to be implemented in the child classes. If abstract methods are not implemented it will throw an error.

Question 15.
What is an Interface?
Answer:
An interface is a contract that defines the signature of the functionality. It looks like a class but has no implementation. It has only an empty definition of methods, functions, events, and indexers.

Interfaces provide the forced implementation. For instance, in the below code snippet we have created a simple interface called ” id compulsory”. The below classes who implement interface “id compulsory” have to provide an implementation for “ExecSgi”.

interface IDbCompulsory
{
       void ExecSql();
}
public class SQLServer: IDbCompulsory
{
       public void ExecSql( )
{
// Here code for firing SQL Server SQL statements
// are written
}
}
public class Oracle: IDbCompulsory
{
      public void ExecSql()
      {
          // Here code for firing Oracle SQL statements
         // are written
      }
}

Question 14.
Does the interface have an accessibility modifier?
Answer:
All elements in the Interface should be public. So no accessibility modifier is required.

Question 15.
Can we create an object of the abstract class or an interface?
Answer:
No.

Question 16.
What is the difference between abstract classes and interfaces?
Answer:

Abstract class Interface
Implementation Some methods in abstract classes can have implementation. All methods, functions, properties in interfaces have to empty compulsorily.
Scenario Abstract classes are used when we want to share a common functionality in the parent-child relationships. Interfaces are used to define contracts, enforce standardization, decoupling, and dynamic polymorphism.
Variable declaration We can declare variables. In interface, we cannot declare variables.
Ingeritance VS Implementation Abstract classes are inherited. Interfaces are implemented.

Question 17.
An abstract with only an abstract method, how is it different from interfaces?
Answer:
If you define all methods, functions, properties as abstract in abstract class it inhibits the same behavior as an interface.

Question 18.
If we want to update the interface with new methods, what is the best practice?
Answer:
The biggest use of the interface is to ensure that strict contract is followed between clients and components. So that when changes happen on the components clients do not have to change too much. In real-world contracts between two parties do not change which implies that interfaces should also not change.

So if you want to add new methods or change methods in interfaces the best practice is to create new interfaces by inheriting. With this approach, your older client who is using the interface stays happy and the new clients who want those new or changed methods get the benefits of the new functionality.

Let’s consider you have a simple interface called ” view” which helps you to view data. Below is the code for the same. Let’s consider that this interface is consumed by many clients.

interface IView
{
public void View( );
}

Over a period of time some users demand “Edit” functionality as well but the rest of the users are happy with the ‘View” functionality and they do not want them to get affected by these changes. Now if you go and change this interface (“IView”) as shown in Figure 3.2 you will be disturbing everyone.

So the best option would be to add a new interface, i.e., “lEdit” which inherits from “IView”. So the “lEdit” will have the functionality for “Edit” as well as “View” because it’s also inheriting from “IView”. And the clients who are consuming “IView” do not need to update as “IView’ is not changed at all.

OOP Interview Questions in . NET chapter 3 img 2

interface IEdit: IView
{
public void Edit();
}

So putting this whole story in one single sentence for the interviewer.

Interface once fixed should not be changed. If we ever have to add new functions, new interfaces 
should be created so that we do not break compatibility with old clients.

Question 19.
What is a delegate?
Answer:
Delegate is an abstract pointer to a function or method. In other words, you can create a pointer that points to a method or function and then pass that pointer wherever you wish and invoke the function/ method.

Question 20.
How can we create a delegate?
Answer:
Creating a delegate is a four-step process:
  • Declare a delegate
  • Create an object reference
  • Point the reference to the method
  • Invoke the method via the delegate
Below is the code snippet for the same.
// Declare a delegate
public delegate int PointToAdd(int i, int y) ;
// Create a reference pointer
PointToAdd objpointer = null;
// Point to the method
objpointer = Add;
// Invoke the function/method
objpointer.Invoke(10, 20);
Question 21.
What is a multicast delegate?
Answer:
Normally when you create a delegate, your delegate points to only one function or method. In case you want to point to multiple functions and invoke them sequentially, you need to use the multicast delegate.
To point to multiple functions using delegate pointers we need to use the “+=” sign as shown in the below code snippet.
ptrcall += Method1;

ptrcall += Method2;
Question 22.
What are Events?
Answer:
Events are a higher level of encapsulation over delegates. Events use delegates internally. Delegates are naked and when passed to any other code, the client code can invoke the delegate. The event provides a publisher/subscriber mechanism model.
So subscribers subscribe to the event and the publisher then pushes messages to all the subscribers. Below is a simple code snippet for the same:
Create a delegate and declare the event for the same.
public delegate void CallEveryone( );

public event CallEveryone MyEvent;
Raise the event.
MyEvent( );
Attached client methods to the event are fired/notified.
obj. MyEvent += Function 1;
Question 23.
What is the difference between delegates and events?
Answer:
They(l) What is the difference between delegate and events? can not be compared because one derives from the other.
  • Actually, events use delegates at the bottom. But they add an extra layer of security on the delegates, thus forming the publisher and subscriber model.
  • As delegates function as pointers, they can move across any client. So any of the clients can add or remove events, which can be confusing. But events give the extra protection/encapsulation by adding the layer and making it a publisher and subscriber model. 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.
Question 24.
Do events have a return type?
Answer:
No, events do not have a return type.
Question 25.
Can events have access modifiers?
Answer:
Yes.
Question 26.
Can we have shared events?
Answer:
Yes, you can have shared events, do note only shared methods can raise shared events.
Question 27.
Explain Action, Func, Anonymous methods, and Lambda expressions.
Answer:
Left to the readers.
Question 28.
What is shadowing?
Answer:
Shadowing replaces the complete element of the parent class. For instance, you can see in the below sample code where the cisParent has a variable int “i”, which is replaced by the child class child by a method “i”. In other words when you refer to the parent object “i” it is a variable and when you refer to the child object” i” it is a method.
class clsParent
{
      public int i=0;
}
class cisChild: cisParent
{
     public new void i()
     {
          Console.WriteLine("Hey i became a method");
     }
}

Question 29.
What is the difference between shadowing and overriding?
Answer:
Overriding redefines only the implementation while shadowing redefines the whole element.

Question 30.
If we inherit a class do the private variables also get inherited?
Answer:
Yes, the variables are inherited.
Question 31.
How can we stop the class from further inheriting?
Answer:
We can stop the class from further inheriting by using the “sealed” keyword. For instance below is a sample code where we have a class called “Human” which is further inherited to create a “Male” or “Female” class.
Now the below code is great but we do not have anyone to further inherit from the “Male” or “Female” class. In simple words, “Male” and “Female” are the last legs in this inheritance hierarchy. This can be done by using the “sealed” keyword.
public class Human
{ }
public sealed class Male: Human
{ }
public sealed class Female: Human
{ }

If anyone tries to inherit the sealed classes an error appears” cannot derive from sealed type”.

Question 32.
What is the use of the “Must Inherit” keyword in VB.NET?
Answer:
If you want to create an abstract class in VB.NET it is done by using the “Must Inherit” keyword. You cannot create an object of a class, which is marked as “Must Inherit”. When you define the “Must Inherit” keyword for a class, you can only use the class by inheriting it.
Question 33.
What are the similarities between class and structure?
Answer:
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 the interface.
  • Both of them can have constructors with and without parameters.
  • Both can have delegates and events.
Question 34.
What is the difference between class and structure?
Answer:
Following are the key differences between them:
  • Structures are value types and classes are reference types. So structures use stack and classes use heap.
  • Structures members cannot be declared as protected, but class members can be. You cannot do inheritance in structures.
  • Structures do not require constructors while classes require.
  • Objects created from classes are terminated using Garbage Collector (GC). Structures are not destroyed using GC.
Question 35.
When to use structures and when to use classes?
Answer:
You will use structures when:
Point 1: If you want to represent a custom value type. This custom value type is derived from primitive data types (int, double). Some of the examples of custom types are coordinates (which have X, Y), complex numbers (which have real and imaginary components). You can also term these things as value objects or technical objects. Technical objects do not represent real-world objects like customers, suppliers, invoices, etc.
Point 2: If you want to have a low memory footprint. For instance, let’s say you want to plot a graph. To plot a graph you need to have 100’s of objects created so that you can represent coordinates. Now if you create a class and generate those 10Q’s of objects you end up putting a lot of load on your garbage collector. If you create a “struct”, it is a value type as shown in Figure 3.3. So they get created and destroyed immediately. Thus putting less load on memory.
For all other scenarios use a class.
OOP Interview Questions in . NET chapter 3 img 3
Question 36.
What does virtual keyword mean?
Answer:
The signifies that method and property can be overridden by the child classes.
Question 37.
What are shared (VB.NET)/Static(C#) variables?
Answer:
When you define a variable as static or shared only one instance of the object or variable is created.
Question 38.
What is an enum and what are the benefits of using it?
Answer:
enum helps to define, manage and assign constants in an effective way. Now the below sample code is good but the level values are not readable.
if (level == 0)(Console.WriteLine(“Below quality”);}
else if (level == 1)(Console.WriteLine(“Moderate quality”);}
else if(level == 2)(Console.WriteLine(“High quality”);}
Now by declaring a simple enum called Quality as shown below.
enum Quality
{
Low = 0,
Moderate = 1,
High = 2
};

Our code would look more readable as shown below. The other big benefit is if we change the numeric values of quality we do not have to change throughout the project. So we can go a change the Low quality to 1 and no change in code is required.

if (level == Quality.Low)(Console.WriteLine(“Below quality”);}
else if (level == Quality.Moderate)(Console.WriteLine(“Moderate quality”);}
else if(level == Quality.High)(Console.WriteLine(“High quality”);}
So summarizing enum has two big benefits:
  • Code becomes more readable.
  • Easy to change constants without affecting the project. Easy maintenance.
Question 39.
What is the use of Flags in the enum?
Answer:
“Flags” is an enum attribute. If you want to set multiple values to an enum we need to use Flags.
[Flags]
enum MyColors
{
Green = 0,
Red = 1,
Blue = 2
} ;

In the below code we are setting “MyColors” enum to “Blue” and “Green” valuess.

MyColors color = MyColors.Blue | MyColors.Green;


if ((color & MyColors.Blue) == MyColors.Blue)
{
Console.WriteLine(" Blue");
}
if ((color & MyColors.Green) == MyColors.Green)
{
Console.WriteLine(" Green");
}

Question 40.

How can we loop through Enum values?
Answer:
We can use the “Get values ( )” method of the “Enum” class which returns an array of Enum values.
varx = Enum. GetValues(typeot(MyColors));

Question 41.
What is the use of the “Enum. parse” method?
Answer:
Interviewers can also put this question differently on how to convert a string to an Enum value.

OOP Interview Questions in . NET chapter 3 img 4

Many times we would like to convert a string into Enum objects. For example, let’s say you have a color Enum and you would like to pass string “Red” and get Enum object “color. Red”.

“Enum. parse” method parses the string to an Enum value. Like in the below code we pass the “Red” string value and it gets typecasted to enum which has green Enum as a constant.

MyColors EnumColors = (MyColors)Enum.Parse(typeof(MyCo!ors), “Red”);

Question 42.
What are nested classes?
Answer:
Nested classes are classes within classes.
If you create the child class object which constructor will fire first?

public class class1
{
public class1( ){ }
}
public class class2: class1
{
public class2( ){ }
}

Parent class constructor will fire first.

Question 43.
In what instances you will declare a constructor to be private?
Answer:
When we create a private constructor, we cannot create an object of the class. Private constructors are used when we want only a single instance of the class to be created and externally no one can use the ‘ new’ keyword to create the object.

Question 45.
Can we have different access modifiers on getting/set methods of a property?
Answer:
Yes, we can have different access modifiers. The below code will compile perfectly well.

public string CustName
{
get
{
return _Custname;
}
protected set
{
Custname = value;
}
}

Question 46.
How can you define a property read-only for the external world and writable in the same assembly?
Answer:

This question is a variation to the previous question. So it's possible that the interviewer 
  can ask the previous question in this format.

Let’s first try to understand this question. Let’s say if you have a class called “Customer” with a property “CustomerCode”. Now you want that anyone can read from the “CustomerCode” property but this property can only be set from within the assembly.
In other words, anyone can run the below code.

Customer obj = new Customer();
string x = obj.CustomerCode;

But the setting of the value can be only done from within assembly. The below code will run only if it is within the assembly and it will throw an error if it is external to the assembly.

Customer obj = new Customer( );
obj. CustomerCode - “c001”;

This can be achieved by having different access modifiers for “set” and “get” properties on the “CustomerCode” property.

So for the “get”, we will have public access modifiers and for “set” we will apply internal access modifiers. Now because “get” is public this property can be read anywhere and because the “set” is internal it can only be accessed from within assembly. Below is the code for the same.

class Customer
{
      private string _CustomerCode = " ";
      public string CustomerCode
      {
           get { return _CustomerCode; }
           internal set { _CustomerCode = value; }
      }
}

Question 47.
Will the final run in this code?
Answer:
In the below code in the try statement we have a return statement, will the finally block still run.

public static void Main()
{
    try
   {
        // Some code
        return;
  }
  finally
 {
        //Will this run
  }
}

Yes, the final code will run even though there is a return statement in the trial. The final block will run irrespective of what happens in the try block. That’s the reason why finally block is a good place to put clean up code.

Question 48.
What is an Indexer?
Answer:
Many times classes have contained (aggregated or composed) collections. For example, in the below code you can see we have a customer class that has an Address collection.

public class Customer
{
private List<Address> Addresses = new List<Address>( );
}

Now let’s say we would like to fetch the addresses collected by “Pincode” and “PhoneNumber”. So the logical step would be that you would go and create two overloaded functions one which fetches by using “PhoneNumber” and the other by “PinCode”. You can see in the below code we have two functions defined.

public Address getAddress(int PinCode)
{
       for each (Address o in Addresses)
       {
              if (o.Pincode == PinCode)
              {
                   return o;
              }
       }
       return null;
}
public Address getAddress(string PhoneNumber)
{
      for each (Address o in Addresses)
      {
            if (o.MobileNumber == PhoneNumber)
            {
                   return o;
            }
      }
      return null;
}

Now on the client-side, your code would look something as shown below.

Customer Customers = new Customerf);
Customers.getAddress(1001);
Customers.getAddress(“9 090”) ;

Now the above code is great but how about simplifying things further. How about something more simple as shown in the below code. In other words, the class itself is to be indexed.

Customer Customers = new Customer();
Address o = Customers[10001]; o = Customers[“4320948”];

You can see in the Figure 3.5 where we can have two overloaded indexers “Pincode” and “PhoneNumber”.

 

OOP Interview Questions in . NET chapter 3 img 5

This can be achieved by using an indexer. There are two things we need to remember about indexers:

  • “Indexer” is defined by using the ” this” keyword.
  • “Indexer” is a property so we need to define set and get for the same.

Below is the code implementation for the indexer. You can see we have used the “this” keyword with two overloaded functions one which will fetch us address by using the “PhoneNumber” and the other by using “PinCode”.

public class Customer
{
       private List<Address> Addresses = new List<Address>( );
       public Address this[int PinCode]
       {
           get
           {
                  for each (Address o in Addresses)
                  {
                         if (o.Pincode == PinCode)
                         {
                              return o;
                         }
                 }
                 return null;
            }
}
public Address this[string PhoneNumber]
{
      get
      { 
            for each (Address o in Addresses)
            {
                  if (o.MobileNumber == PhoneNumber)
                  { 
                           return o;
                  }
          }
          return null;
         }
     }
}

Once you put the above “indexer” code you should be able to access the address collection from the Customer object using an indexer ” [ ]” as shown in Figure 3.5.

Summarizing in one sentence: Indexers help to access contained collection within a class using a simplified interface. It is syntactic sugar.

Question 49.
Can we have a static indexer in C#?
Answer:
NO.