Important C# Interview Questions and Answers

In this blog, I have collected important C# interview questions and answers and their answers, which will help you in preparing your interview. If you are an ASP.Net or ASP.Net Core programmer or developer who is preparing for an interview, then believe that you are reading the right blog.

Table of Contents

Whether you are a fresher or have ASP.Net or Dot Net Core development experience, the C# interview questions given below will prove to be very beneficial for you. So, without delay, let’s read each interview question of C# programming language and its answer as these are some essential and frequently asked interview questions and answers.

Q. What is Object Oriented Programming?

Please read here about Object Oriented Programming.

Q. What are OOPS Concepts?

It is a frequently asked question in C# interviews and ASP.Net interviews. OOPS concept is the most asked question in an interview for C#, Java, ASP.Net developer role.

Please read here about the OOPS concept in detail. 

Q. Class Vs Struct

ClassStruct
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 inheritanceStruct do not support inheritance
Class have default constructorStruct cannot have default constructor

Q. What is Interface?

Interface is one of the most asked C# interview questions.

The interface is similar to the class but the Interface contains only Abstract methods i.e. we can only declare methods in the interface and no method body can be defined in the interface.

All methods declared in an interface should be implemented by the child class of that interface.
By default all members of an interface are public and abstract.

Method declaration in Interface –

void Show(string name);
int Add(int a, int b);

We can’t declare a field or a variable in an interface.
An interface can be inherited from another interface.

Look at the below sample code :

Interface1 contains a single method GetEmployeeList()

interface Interface1
{
    void GetEmployeeList();
}
interface IDepartment : Interface1
{
    void GetEmployeeByDepartment(int deptID);
}

IDepartment interface contains one method GetEmployeeByDepartmentID(int deptID)

Class Test implements Interface1 so it has to define only one method i.e. GetComployeeList()

Class Test1 implements IDepartment interface so it has to define GetEmployeeByDepartment(int deptID) and also GetComployeeList() because as shown above IDepartment inherits Interface1. So IDepartment contains 2 methods.

Note: If you are implementing a method of an interface in a class, then the method must be public in that class.

class Test : Interface1
    {
        public void GetEmployeeList()
        {
            throw new NotImplementedException();
        }
    }
    class Test1 : IDepartment
    {
        public void GetEmployeeByDepartment(int deptID)
        {
            throw new NotImplementedException();
        }
        public void GetEmployeeList()
        {
            throw new NotImplementedException();
        }
    }

Single inheritance is supported in C# but multiple inheritance is not supported using classes. i.e. 
A class can not have multiple base classes.

class B
{
}

class C
{
}

 The below is incorrect, a class can not have multiple base classes.

Class A: B,C
{
}

Q. Why is Multiple Inheritance not supported using class?

It is a very important C# interview Question. In the above sample code, class B and class C may contain the same method ABC()
So, if class A inherits class B and class C then the ABC() method can create ambiguity in class A. This is the reason multiple inheritance is not supported using class.

Multiple inheritance can be supported using the interface. 

Look at the below 2 interfaces.

interface Interface1
{
    void GetEmployeeList();
}
interface IDepartment
{
    void GetEmployeeList();
    void GetEmployeeByDepartment(int employeeID);
}

class Program implements 2 interfaces Interface1 and IDepartment.
 You may notice GetEmployeeList() method is in both interfaces but in the class Program, there is only one implementation. So no ambiguity and no compile time error.

class Program : Interface1, IDepartment
{
    public static void Main(string[] args)
    {
        Program obj = new Program();
    }
    public void GetEmployeeByDepartment(int employeeID)
    {
        throw new NotImplementedException();
    }
    public void GetEmployeeList()
    {
        throw new NotImplementedException();
    }
}

Q. How to implement the interface explicitly?

using InterfaceName.MethodName
See the sample code below.

class Program : Interface1
{
    public static void Main(string[] args)
    {
        Program obj = new Program();
        Interface1 i = obj;
        i.GetEmployeeList();
    }
    void Interface1.GetEmployeeList()
    {
        throw new NotImplementedException();
    }
}

Q. Differences between Interface and Abstract Class

This is also an important C# interview question.

InterfaceAbstract Class
If we don’t know about implementation then go for InterfaceIf we know about implementation then go for Abstract class
Every method in an Interface is public by default.In Abstract class every method need not to be public.
Abstract class may contain Abstract or non-abstract (concrete) methods.
Interface is used in multiple design principles.Abstract class is also useful in SOLID design principle.
An interface cannot contains constructorAbstract class can contains constructor

Q. Abstract vs Sealed Class

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

Q. Constructor vs Destructor

A method with the same name as the class name is called constructor.
Constructors are by default public.
It doesn’t return anything.
The constructor name is the same as the class name.
A constructor with no arguments and nobody is called a default constructor.
We can create private constructors.

These are special methods of a class which is automatically called as soon as the object of the class is created.

3 types of of constructors are Default Constructors, Parametrized Constructors, and Copy Constructors.

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 the Garbage Collector.

Q. What is Collection in C#?

Collection classes are responsible for data storage. The collection supports queue, stack, list, hash table etc. Classes that come under System.Collection namespace: ArrayList, HashTable, Queue

For more details see this link What is Collection

Q. What is a reflection in C#?

Reflection in C# is used to get metadata of an assembly. Classes in Reflection use System.Reflection namespace.

The below C# code is used to get assembly info, qualified name, base type etc.

use the below namespace in your code:

using System.Reflection;
Type tp = typeof(Program);
Console.WriteLine(“assembly - ” +tp.Assembly + “qualified name - ” +tp.AssemblyQualifiedName + “attributes - ” +tp.Attributes + “base type - ” +tp.BaseType + “declaring type - ” +tp.DeclaringType + “full name - ” +tp.FullName + “is abstract - ” +tp.IsAbstract + “is class- ” +tp.IsClass + “is enum- ” +tp.IsEnum);

Q. What is get and set in C#?

Get and Set in C# is an auto property or auto-implemented property which is a shorthand to write property. This is a very important C# interview question.

private string _Login; //Backing Field
public string Login //Property
{
    get
    {
        return _Login;
    }
    set
    {
        _Login = value;
    }
}

Q. What is Abstract Class?

  • Abstract classes are incomplete and must be implemented in derived classes.
  • An abstract class can contain Abstract or non-abstract methods.  
  • Abstract methods do not have any implementation in the Abstract class and must be implemented in the derived class.
  • In the child class, it is optional to implement the abstract method of a parent class.
  • An abstract class can not be instantiated. 
  • You can not declare an abstract class outside an abstract class.
  • It can not be declared sealed.  
  • An abstract method must declare in Abstract class only.

An abstract method is used for Dynamic Polymorphism.

A static member can not be marked as virtual, override or abstract (See below code)

abstract class abs1
{
    public static abstract int AddNum1(int a, int b); // Error in this line

    int AddNum2(int x, int y)
    {
        return x + y;
    }
}

Abstract Class Example:

namespace MorePractice
{
    class Program : abs1 // Program inheriting abstract class abs1
    {
        static void Main(string[] args)
        {
            Program objp = new Program();
            Console.WriteLine(objp.AddNum1(5, 10));

        }

        public override int AddNum1(int a, int b) //overriding abstract method declare in abstract class abs1
        {
            return a + b;
        }
    }

    abstract class abs1 // abstract class abs1
    {
        public abstract int AddNum1(int a, int b); //abstract method with declaration only

        public static int AddNum2(int x, int y) //non-abstract method
        {
            return x + y;
        }

    }
}

Q. What is sealed class?

An abstract class can not be declared sealed.  Sealed class can not be inherited, but sealed class can inherit other class. It means a sealed class can not be a base class. Sealed keyword in a method must be used with override keyword.

Q. What is an interface?

Q. Data Hiding in C#?

Data Hiding or Data Encapsulation is used to hide data from the outer world.
For eg: If you are buying a new handset you don’t bother about its internal engineering or how signal converts and received by a handset.

Q. Data Abstraction in C#?

Data Abstraction is hiding complexity and showing what is necessary.
For eg: If a user buys a new mobile phone he/she looks for color, mp3, camera, sound quality etc. He/she doesn’t care about internal circuits.

An example of Abstraction in C# Code:

public class Pigeon : Bird
{
    public override void fly()
    {
        Console.WriteLine(“Pigeon Can Fly”);
    }
}

public class Crow : Bird
{
    public override void fly()
    {
        Console.WriteLine(“Crow Can Fly High”);
    }
}


abstract class Bird
{
    public abstract void fly();
}

Q. What is a generic class in C#?

Generic allow you to work with class and method of any data type. In generic data type determines at run time only.

Consider below snippet:

class Test<T>
{
    T val;
    public Test(T t)
    {
        this.val = t;
    }
    public void Print()
    {
        Console.WriteLine(this.val);
    }
}


class Program
{
    static void Main(string[] args)
    {

        Program objP = new Program();

        Test<int> objT = new Test<int>(10);
        objT.Print();


        Test<string> objT1 = new Test<string>(“test”);

        objT1.Print();
    }
}

In above example, there is a single method in Generic class Test of type T and gives out put based on provided data type i.e. int or string.

Q. What is Post back property?

Post back is used to send back the web form on the web server with the data in its control for further processing. After processing on the server the page will be again loading into the memory. This whole process is known as the round tripping of the page.

Q. What is a value type and reference type?

In Value, type space is allocated in memory to store variable.
In reference type address of the object is stored in stead of data itself.

Value Type:

int i= 20; //value of i i.e. 20 is stored in memory

Reference Type:

int[] arr = new int[20]; 

Q. What is boxing and unboxing?

Boxing- When a value type is converted in reference type.

int i = 67; // i is value type 
object ob = i; // variable i is boxed

Unboxing- When a reference type is converted into a value type.

Performance Impact:
when using value type in a method parameter, a copy of each parameter is created into a stack. If it is a large data type, then its going to impact on performance.
So to avoid this issue better to use reference type by using ref keyword.

Code Snippet:

class A
        {
            public static void PrintDataValueType(int i)
            {
                Console.WriteLine(i);

            }

            public static void PrintDataRefType(ref int i)
            {
                Console.WriteLine(i);

            }

        }

class Program
    {
        static void Main(string[] args)
        {

            Program objP = new Program();

            int i = 100;
            A.PrintDataValueType(i); //Call with Value Type parameter

            A.PrintDataRefType(ref i); // Call with Reference Type parameter
         }
     }
 static void Main(string[] args)
        {
            int count = 10;
            object obj = count;  //Boxing
            int newcount = (int)obj; //Unboxing
        }

Q. What is a partial class in C#?

A partial class is used to split a class in 2 or more source file, see below code.

public partial class Hotel
    {
        public void DoOrder()
        {
            Console.WriteLine("Order Placed");
        }
    }

    partial class Hotel
    {
        public void BillPayment()
        {
            Console.WriteLine("Bill Paid");
        }
    }

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

Good Practice:

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

Q. String vs StringBuilder

String is immutable.
But, 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);


        }

Example of String builder

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

Q. What is Delegate 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);
        }

Q. Sealed vs 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

 Q. What is Partial Class?

Partial class allow developers to split the class into 2 or more source files.

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

Q. What is 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#”);
           
        }
       
    }

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

Q. 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;
        }

Q. What is Enum in C#?

Enum is a type with a set of related named constants. Enum type can be int, float, double.
By default first enumerator has value 0.
Let’s see Enum by example.

 public enum days
   {
       Monday,
       Tuesday,
       Wednesday,
       Thursday,
       Friday,
       Saturday,
       Sunday
   }


   public class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(days.Monday);
            Console.WriteLine((int)days.Monday);          
         }
    }

Enum is used to make the code much readable and understandable.

Q. Explain Custom Logging in C#.

Follow this ink –  http://www.sharepointcafe.net/2015/06/exception-handling-in-c-sharp-dot-net.html

Q. Access modifier in C#.

Default access modifier in C# is internal

Below are access modifier available in C#.

Public– No restriction, can be access from anywhere in the project.

Internal– Access limit to assembly.

Protected– Access limit to class and derived class. Protected variable is accessible in same partial class.

Private– Access limit to the current scope where it is defined. A private variable is accessible in same partial class. See below code

public partial class Test
    {
       protected int a=10;
        private void Print()
        {
            Console.WriteLine(a);
        }
    }

   partial class Test
    {
        public void Print1()
        {
            Console.WriteLine(a);
        }
    }

Q. What is Static and Dynamic Polymorphism?

Static Polymorphism is also called as Compile time Polymorphism or Early binding or Method Overloading.
In Static Polymorphism, two methods will have the same name but different parameter. See below example

public class New
    {
        public int Add(int a, int b)  //Method with two int parameter
        {
            return a + b;
        }

        public string Add(string x, string y) //Same method name but with two string parameter
        {
            return x + y;
        }
    }

Dynamic Polymorphism or Method Overriding or Late Binding means same method name with same parameters.

We can override a method in the base class using override keyword in derived class method.

Example:

public class New
    {
        public virtual int Add(int a, int b)
        {
            return 10;
        }

       
    }

    public class New2:New
    {
        public override int Add(int a, int b)
        {
            return 20;
        }
    }

Q. What is preprocessor directives in C#?

Preprocessor Directives gives instruction to the compiler about what to do before actual compilation.

For Eg:
Using below code you can tell the compiler to execute code only if the mode is in Debug else do not execute.

#if DEBUG
            Console.WriteLine(“This is in Debug Mode”);
#endif

Q. What is delegate and events in C#?

A delegate is a reference type and refers method.
Declaration of Delegate

  public delegate void MyDelegate();

C# code without delegate:

public class Program
    {
        static void Main(string[] args)
        {

            Program.Add(20, 10);
        }

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

C# code with delegate:

public delegate void MyDelegate(int a, int b);
    public class Program
    {
        static void Main(string[] args)
        {

            MyDelegate del = new MyDelegate(Add); //Holding the reference of Add method
            del(10,20);
        }

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

Q. Virtual keyword in C#

Virtual or abstract members can not be private.

public class Class1
    {
private virtual void Method() //method can not be private as virtual method must be accessible in other class to override
        {
            Console.Write(“Hello”);
        }
    }

Below code will give an error:

Can not change access modifiers when overriding inherited member

See below code:

public class Program:Class1
    {
      static void Main(string[] args)
        {
            
        }
        public override void Method()//Access modifier is changed from protected to public
        {
            base.Method();
        }
    }

    public class Class1
    {
       protected virtual void Method() //Here virtual method is protected
        {
            Console.Write(“Hello”);
        }

    }

Q. Class vs Struct

Class is a reference type, Struct is a value type.
An object of the class holds the reference to the memory.
A struct does not support inheritance but class support.
A struct can not have default constructor but a class has.

Q. Primitive data type vs non-primitive data type

A primitive data type is predefined by the system for eg- byte, short, int, float, double long etc.
A non-primitive data type is user defined for eg – class, struct, interface etc.

Q.Convert and Parse and TryParse

Convert vs Parse

Compile Time Error

    int a = 10;
            int b = Convert.ToInt32(a);
            int c = int.Parse(a); //Error-The best overloaded method match for ‘int.Parse(string)

Run Time Error

    int a = 10;
            string ss = null;
            int b = Convert.ToInt32(ss);//b = 0
            int c = int.Parse(ss);//Error – ArgumentNULLException was handled

Try Parse
It converts a string to integer and returns true if success else returns false.

Q. What is Garbage Collection in C#?

Garbage collection is a part of CLR (Common Language Runtime) and it is used for automatic memory management. GC reclaims unused object, clears memory and make them available for future uses.

Generations of Garbage collection:

Generation 0: It contains a newly created object. Generally, hold a temporary object.

Generation 1: It contains an object of long live duration and transfers to Generation 2.

Generation 2: It contains longest-lived object, generally object at the application level.

Garbage Collector Phases:

Marking Phase: In this phase, GC finds and create a list of active objects.
Relocation Phase: In this phase GC updates the reference to the objects that will be compacted.
Compacting Phase: In this phase, GC reclaims the memory occupied by a dead object.

Q. Constant vs Readonly

Const Keyword

  • Const is purely constant and can not be changed through out the application life cycle.
  • It requires a value when declared.

Readonly Keyword

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

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

Q. 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);
        }

Q. 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);
            }

Q. 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);
       }
   }

Q. What is the output for below sample code?

   string a = new string(new char[] { ‘O’, ‘k’ });
            string b = new string(new char[] { ‘O’, ‘k’ });
            Console.WriteLine(a == b);
            Console.WriteLine(a.Equals(b));
            object c = a;
            object d = b;
            Console.WriteLine(c == d);
            Console.WriteLine(d.Equals(d));

Q. What is SOLID Design Principle?

A C# or .NET interview is not completed without SOLID Design principle, this is very important concept for freshers as well as experience developers.

SOLID design principle is used to develop a flexible, testable and maintainable applications. It consists of 5 principles.

  • S (Single Responsibility) – A class should be created for a single specific purpose. It means a class should not be responsible for multiple tasks.

The very basic example to understand this principle is User Registration process. In UserRegisteration Service class, if we write code which send welcome message or credential details, this violates Single Responsibility principle.

In stead, create a different class for Email Service and then after successful registration process we may call function written in Email Service to send email to users.

  • O (Open Close Principle) – This principle says that a class or function should be open for extension but should be closed for modification.

Consider Below example –

In below code snippet, suppose a new docType is required then this class needs a modification and we need to add one more condition to achieve this. This violates the Open Close Principle.

    public class ExportDocument
    {
       public void Export(string docType)
        {
            if(docType == "pdf")
            {
                //Export Document in PDF Format
            }

            else if (docType == "word")
            {
                //Export Document in Word Format
            }

            else if (docType == "excel")
            {
                //Export Document in Excel Format
            }
        }
    }

To overcome this issue, we can create an interface.

 public interface IExportDocument
    {
        public void Export();
    }

Next, create classes as per document type to export and inherit it from the interface, created above.

 public class ExportDocumentInPDFFormat : IExportDocument
    {
        public void Export()
        {
            //Export Document in PDF format
        }
    }

    public class ExportDocumentInWordFormat : IExportDocument
    {
        public void Export()
        {
            //Export Document in Word format
        }
    }

    public class ExportDocumentInExcelFormat : IExportDocument
    {
        public void Export()
        {
            //Export Document in Excel format
        }
    }

In case a new document type is required to export then simply create a class as shown below and inherit it from IExportDocument. In this way, non of the existing class is required to modify and we follow Open Close Principle.

 public class ExportDocumentInCSVFormat : IExportDocument
    {
        public void Export()
        {
            //Export Document in CSV format
        }
    }

We can use abstract class instead of interface to achieve this principle.

  • L (Liskov substitution Principle) – If S1 is a subtype of T1 then object of T1 may be replaced with object of S1. It means derived types can be substitute for the base types. This principle can be achieved with the help of interface or abstract class. 
  • I (Interface Segregation Principle) – The Interface Segregation Principle says that there should be multiple Interfaces instead of single interface. This will not force the client to implement interfaces they do not require.
  • D (Dependency Inversion Principle) – This SOLID design principle says that a high level module shouldn’t depend upon low level module. It basically avoids tight coupling and help us to develop an application which code is testable, maintainable.
Read this article - SOLID Design Principle in C#

Q. What is Tupple in C#?

Tupple was introduced in .NET 4.0. It is a kind of data structure which can hold members of different data types.

Normal syntax to declare Tuple.

Tuple<T1, T2, T3, T4, T5, T6, T7 .....Tn> T1 = new T1<T1, T2, T3, T4, T5, T6, T7.....Tn>()

Example of Tuple

 Tuple<int, string, string,int> person =
                         new Tuple<int, string, string, int>(1, "Swami", "Vivekanand",10);
 Console.WriteLine(person.Item1);

Q. What are differences between Array and Jagged array?

Q. Serialization vs DeSerialization

Q. Explain Multiple Inheritance in C#

Q. Explain Finalize() and Dispose() in C#

Q. What is Object Pool in .NET?

Q. What is nullable type in C#?

Q. What are indexers in C#?

Q. Explain Early Binding and Late Binding.

More interview questions based on C# 9.0

Q. What is Record Type?

Q. Explain Function Pointers in C#

Q. What is Init Only Property?

Q. What is Value Equality?

Q. What is pattern matching?

Q. Please explain Top level statements

Hope these C# interview questions and their answers will help you to crack any C#/ ASP.Net interview.

Do more practice and keep following SharePointCafe.Net

For more interview Questions and answers, please visit this link – Interview Questions and Answers – SharePointCafe.Net

Leave a Comment

RSS
YouTube
YouTube
Instagram