Oops interview questions and answers

Interview questions of OOPS (Object Oriented Programming System)



1. Class Vs Struct


Class
Struct
A class is a reference type.
A struct is a value type.
When an object of the class is created, the variable to which the object is assigned holds only a reference to that memory. 
When a struct is created, the variable to which the struct is assigned holds the struct's actual data. 
Classes and structs can inherit multiple interfaces. 
Classes and structs can inherit multiple interfaces. 
Class Support inheritance
Struct do not support inheritance
Class have default constructor
Struct cannot have default constructor

2. Abstract vs Sealed Class

Abstract Class
Sealed Class
An abstract class cannot be instantiated. 
A sealed class cannot be used as a base class. For this reason, it cannot also be an abstract class. 
The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share.
Sealed classes prevent derivation. Because they can never be used as a base class.
Abstract methods have no implementation, so the method definition is followed by a semicolon instead of a normal method block. Derived classes of the abstract class must implement all abstract methods.

When an abstract class inherits a virtual method from a base class, the abstract class can override the virtual method with an abstract method.





3. Constructor vs Destructor

A method with same name as class name is called constructor.
Constructor by default public.
Constructor will not return anything.
Constructor name is same as class name.
Constructor with no arguments and no body is called default constructor.
We can create private constructors.


Constructor is a special method of a class which is automatically called as soon as object of class is created.



3 types of of constructor Default Constructor, Parametrized Constructor, Copy Constructor



Default constructor:

Public class Employee()

{

Public Employee()

{

}


Parameterized Constructor:
Public Employee(int id, string name, decimal sal)
{
//Assign property
}
}

Copy Constructor:
Employee emp = new Employee();
Emploee emp1 = new Employee(1,"Emp1",10000)
emp1 = emp;
emp1.Name = "KK";
emp1.Sal = 20000;
emp1.ID = "Emp2";
emp = new Employee(emp1); //Copy Constructor

Destructor
It is called automatically when an object is no longer in use. This activity is automatically controlled by Garbage Collector.

4. What is Garbage Collector?
.Net Framework manages the memory deallocation when an object is no longer holding any reference.
GC checks periodically that any object which is no longer holding any reference , then its reclaim that memory.

5. Generation of Garbage Collector

Generation 0: Newly created object. Short lives and collect frequently.
Generation 1: Longer live than Generation 0
Generation 2: Longest live Object for eg - Object at application level which contains static data.

6. Garbage Collector Working Phase

Marking Phase      : Finds and create list of live objects.
Relocating Phase   : Update the references of objects
Compacting Phase : Reclaim the memory occupied by dead objects.

* Garbage collector takes its own time to manage memory. We can use exception handling to manage this by force.

7. Managed and Unmanaged Code

Code developed in .Net framework is refer as managed code as memory allocations happen automatically.

Code developed outside .Net framework is refer as unmanaged code such as code in C++

8. Abstract class vs Interface


Interface
Abstract
Interface has no implementation. It only contains signature.
Abstract Class cannot be instantiated. It allows other class to inherit from.
A class cannot have multiple base class, i.e. a class cannot inherit multiple class. But a class can inherit multiple interfaces.  i.e. Multiple inheritance supported by interface.

Interface cannot have implementation for any of its members.
Abstract can or cannot have the implementation of its members.
Interface members cannot have access modifiers.
Abstract class members can have access modifier.
Interface cannot have any fields.
Abstract class can have fields.

9. Boxing and Unboxing

When we are not sure about what data type we are going to receive, then we use object as data type.
object can hold value for any data type.

Boxing: Value type to reference type.
Unboxing: Reference type to value type.


     static void Main(string[] args)
        {
            int count = 10;
            object obj = count;  //Boxing
            int newcount = (int)obj; //Unboxing
        }


10. Enum

Default data type is int. First element start with zero.
Public enum Days
{
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
}                                                                                                                                                                                                                                                                    
11. Constant vs Readonly

Const Keyword

  • Const is purely constant and can not be changed through out the application life cycle.
  • Const requires a value when declared.
Readonly Keyword
  • Readonly may or may not require a value when declared.
  • Readonly value can be changed in static constructor only.



class Program
    {
        public const int meter=10; //Comple time constant
        public static readonly string TableName; //Runtime constant

       static Program()
        {
            TableName = "Employee_Tbl"; //We can assign readonly value in constructor or any other intial point.
        }
        static void Main(string[] args)
        {
            
            //Code
        }

    }

Read only is better than const in context of performance.

12. ref vs out Keyword


Ref and out keyword in C# is use to pass variables by reference.

Ref is 2 way from caller to callee and back.
//Passing by val
static void Main(string[] args)
        {
            int valinit = 20;
            Add(valinit);
            Console.WriteLine(valinit); // Output = 20
           
        }

        public static void Add(int val)
        {
            val = val + 10;
        }

//Passing by ref keyword
static void Main(string[] args)
        {
            int valinit = 20;
            Add(ref valinit);
            Console.WriteLine(valinit); // Output = 30, because reference is updated in Add() method.
           
        }

        public static void Add(ref int val)
        {
            val = val + 10;

        }

Out is one way , from callee to caller.
Out parameter must be assign before using it.
//Passing by out keyword
static void Main(string[] args)
        {
            int valinit = 20;
            Add(out valinit);
            Console.WriteLine(valinit); //Output = 15, as out variable is defined in Add() method 
           
        }

        public static void Add(out int val)
        {
            val = 5; // You must assign value to out parameter
            val = val + 10;

        }

13. dispose vs finalize vs using block

Dispose method belongs to IDisposable interface.
IDisposable interface. has only one method called "Dispose()"
Dispose() method can be controlled i.e. we can call whenever we want to dispose an object.

public void Dispose()
{
GC.SupressFinalize(this);//This method will remove the object from Finalize queue and will overtake this to dispose method.
}


When we call Destructor , at run time it is going to convert into Finalize or we can say that it will override Finalize method. And that object for which destructor is being called is going to add in Finalize queue.

It will be like
protected override void Finalize()

So we can say that using destructor, Finalize method can be implemented.

GC.collect() - Deallocate all the inactive object memory. It is expensive operation.

Program objP = new Program();
objP = null; //It means now object is inactive and it can be free from memory by GC.


Using block will automatically take care of Dispose() method.

using(Program objP = new Program())
{
//Write code here
}

We can use Database connection with using block.

Good Practice:


  1. Follow using statement to make sure Dispose is called.
  2. Do not implement Finalize or Call Destrcutor unless require.


14. String vs StringBuilder


String
String Builder
String is immutable.
String Builder is mutable.

String Builder is better when manipulating heavy string.

static void Main(string[] args)
        {
            string message = "Hello !";
            message += " How ";
            message += " are ";
            message += " you? ";
            Console.WriteLine(message);


        }

//String builder
       static void Main(string[] args)
        {
            StringBuilder strMessage = new StringBuilder("Hello");
            strMessage.Append(" How");
            strMessage.Append(" are");
            strMessage.Append(" you?");
            Console.WriteLine(strMessage);
        }


15. Delegate and Events in C#

A delegate holds the reference of a method.

public delegate void AddPtr(int a, int b);

        static void Main(string[] args)
        {
             
            AddPtr objPtr = new AddPtr(Add);
            //Either we can call via this
            objPtr.Invoke(10, 5);
            //Or we can call via this
            objPtr(20, 7);        }

        static void Add(int a, int b)
        {
            Console.WriteLine(a + b);

        }


16. Sealed and Virtual Class

Sealed class prevent itself to being inherited by other class.
sealed class ProgramNew
    {

    }

    class ExtendProgram : ProgramNew
    {

    }

If you compile above code, it will throw error. 
Error: cannot derive from sealed type

17. Partial Class

Partial class allow developers to split the class into 2 or more source files.
Below is the example.
public partial class Employee
   {
       public void SalaryProcess()
       {
           //Do coding for salary calculation like basic+hra+medical
       }
   }

   public partial class Employee
   {
       public void TaxCalculation()
       {
           //Do coding for Tax calculation
       }

   }


18. IEnumerable vs IEnumerator

These are the interfaces which help to loop through the collection. Also IEnumerable uses IEnumerator internally.

Lets see below example of C# code.


     List<string> productList = new List<string>();
            productList.Add("TV");
            productList.Add("Mobile");
            productList.Add("Laptop");
            productList.Add("Audio system");
            productList.Add("Tablet");

            IEnumerable<string> enumlist = (IEnumerable<string>)productList;
            foreach (string p in enumlist)
            {
                Console.WriteLine(p);
            }

            IEnumerator<string> enumaratorlist = productList.GetEnumerator();
            while (enumaratorlist.MoveNext())
            {
                Console.WriteLine(enumaratorlist.Current);

            }


19. Late Binding vs Early Binding

20. Array vs ArrayList

Array is a container to store a similar type of data.
Array is strongly type.
Array cannot grow in size once initialize.


ArrayList is not strongly typed.
ArrayList can grow in size.
ArrayList offer , Add, Remove method to work.


21. Array.CopyTo() vs Array.Clone()

22. Indexer in C#

23. Multicast Delegate

24. Equality Operator (==) vs Equals()

25. NULLABLE<> Type


26. Generic, Collection and Indexer in C#

Generic introduces in C# 2.0, Generic is not bound with any data type.

Code to check 2 values without generic
static void Main(string[] args)
        {
            
            bool result = Check.IsEqual("20", "10");
            if (result)
            {
                Console.WriteLine("Equal");
            }
            else
            {
                Console.WriteLine("Not Equal");
            }
            
        }
    }

   public class Check
   {
public static bool IsEqual(object a, object b) //Here boxing/unboxing rule will apply, which is not recommended for such a small comparison
       {
           return a == b;
       }
        
   }




Code to check 2 values with generic
static void Main(string[] args)
        {
            
            bool result = Check.IsEqual("20", "10");
            if (result)
            {
                Console.WriteLine("Equal");
            }
            else
            {
                Console.WriteLine("Not Equal");
            }
            
        }
    }

   public class Check
   {
        
       public static bool IsEqual<T>(T a, T b)
       {
           return a.Equals(b);
       }
   }



27. Serialization

28. Jagged Array

29. Anonymous Type in C#

30. Hashtable and Dictionary

31. Reflection

32. Static Constructor

Static constructor will be invoked only once for any number of instance of a class. Static constructor must be parameterless.

   class Program
    {
        /// <summary>
        /// Static Constructor
        /// </summary>
        static Program()
        {
            Console.WriteLine("Static Constructor");
        }

        /// <summary>
        /// Default Constructor
        /// </summary>
        Program()
        {
            Console.WriteLine("Default Constructor");
        }

        /// <summary>
        /// Parameterize Constructor
        /// </summary>
        /// <param name="msg"></param>
        Program(string msg)
        {
            Console.WriteLine("Hello ! " + msg);
        }

        static void Main(string[] args)
        {
            Program obj = new Program();
            Program obj1 = new Program();
            Program obj2 = new Program("C#");
           
        }
       
    }

O/P- Static Constructor 
         Default Constructor
         Default Constructor
         Hello ! C# 
         

Note: Default constructor executed twice, but static constructor invoked only once even non-parametrized constructor called 2 times. 

Note: We can not create an object of the class which has private constructor.

33. For loop vs Foreach

34. Value Type vs Reference Type

35. Custom Control vs User Control

36. Object Pool in C#

37. Operator Overloading










Comments

Popular

Top 8 C# 6.0 Features

SharePoint Interview Questions and Answers

Calling ASP.Net WebMethod using jQuery AJAX

What is Cloud Computing - A guide for beginners