C# Interview Questions

In this article we’ll cover “C# Interview Questions” which will clear your doubts about C#. NET and helps you in cracking the interview.

What is OOP?

OOP is the abbreviation of Object-Oriented Programming. It is a technique or procedure of writing a program. It is a technique to think real world in terms of objects. Object maps the software model with real world and have the responsibilities and provide services to the application. It has four main pillars.

  • Abstraction
  • Encapsulation
  • Inheritance
  • Polymorphism

What is 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 blueprint of objects. You can say it as a template of object.

Following are the characteristics of class

  • Class is inherited from the System.Object Type
  • The class is a reference type in C#.
  • Classes are usually used for large amounts of data.
  • Classes can be inherited from other classes.
  • A class can be an abstract type.
  • We can create a default constructor.

What is an Object?

It is a basic unit of a system which has attributes, behavior and one identity. Objects are members of a class. Class is a blue print of object and all attributes and behavior of an object are defined by the class definition

All objects have their lifetime (GC collect objects which have weak reference). Objects are created, initialized and once necessary functionalities is performed and later the object is destroyed. Every object has their own state and identity which can differ from instance to instance.

What is abstract class?

We can create an abstract class by decorating it with abstract keyword. Data abstraction is the process of hiding certain details and showing only essential information to the end user. This abstraction can only be achieved with either abstract classes or by interfaces.

Following are the features of abstract class.

  • Abstract class always act a base class and is inherited by other classes.
  • It can contain constructors and destructors.
  • One cannot create an object of abstract class.
  • Abstract class can never be static.
  • Multiple inheritances is not supported in abstract class.
  • Abstract class is used as a design concept in programming and provides a base upon which other classes are built.
  • Abstract class can contain both abstract and non-abstract methods in it.
  • All abstract method of abstract class must be implemented in child class.
  • In C# we have “Abstract” keyword where as in VB.NET abstract classes are created using “MustInherit” keyword.
  • Abstract method does not have a body. Its body is provided or written in the derived class. 

abstract class BankBaseClass 
  public abstract void insertData();    // abstract method
  public abstract void updateData();    // abstract method
  public abstract void deleteData();    // abstract method
  public abstract void showData();      // abstract method

 public void ValidateUser()    // Non abstract method 
    Console.WriteLine("User validated successfully");
// in following class we will inherit abstract class. 
public class Bank : BankBaseClass
  // 'override' keyword is used to use base class methods as shown below
    public override void insertData()
        Console.WriteLine(“Insert data method is called”);
    public override void updateData()
        Console.WriteLine(“Update data method is called”);
    public override void deleteData()
        Console.WriteLine(“Delete data method is called”);
    public override void showData()
        Console.WriteLine(“Show data method is called”);

What is the difference between Interface and Abstract Class in C#?

  • Abstract classes can have both abstract and non-abstract method whereas in Interface all methods are abstract by default.
  • Multiple Inheritance in not feasible with abstract class but feasible with interfaces.
  • In abstract classes “abstract” keyword is used and for interfaces we use “interface” keyword.
  • We can have constructor in “abstract” class but not in interfaces.
  • Abstract class can have static data members, but interfaces cannot.
  • Performance of Abstract class is fast as compared to Interfaces.
  • Abstract class can be implemented fully or partially but Interface are implemented fully.

What are similarities between structure and Class?

Classes and structures have following similarities:

  • Both can have constructors with and without parameter.
  • Both can implement interface.
  • Both support methods, delegates, events, and event handlers. 

What is the difference between a struct and a class in C#? 

  • Class is reference type but struct is value type.
  • Structures are stored on stack but classes use heap for storage.
  • Inheritance is not possible in struct but feasible with classes.
  • Class objects can be cleared using GC.collect (). Structures are not destroyed using GC.

What is Optional Parameter in C#?

The concept of ‘Optional Parameters’ was first introduced in C# 4.0. As name indicate these parameters are Optional Parameters and one is not forced to pass these parameters. User can pass compulsory parameters as mandatory and “Optional Parameters” will take its default value.  If you will pass “Optional Parameters” value, then it will use that value else default value will be considered.

Please check out more on optional parameters HERE

Optional Parameters key points:

  • Optional Parameters are applicable for methods and constructors too.
  • If you will not pass the value to ‘Optional Parameters’ then it will consider its default value.
  • Default value to Optional Parameters are defined in its definition.

Optional parameters code sample:

public  class Program
        public class codeconfig
            static public void CsutomerInfo(string Firstname,
                                           string Lastname,
                                           string DOB = "01/01/2001",
                                           string BankName = "ABC bank" )
                Console.WriteLine("First Name: {0}", Firstname);
                Console.WriteLine("Last Name: {0}", Lastname);
                Console.WriteLine("BankName: {0}", BankName);
                Console.WriteLine("DOB: {0}", DOB);

        static void Main(string[] args)
           codeconfig.CsutomerInfo("Rakesh", "kumar");

What are dynamic type variables in C#?

It is a data type in which you can store any value or object. Type checking for dynamic variables is done at runtime.

     static void Main(string[] args)
         codeconfig obj = new codeconfig();
         dynamic RollNo = 21;            // store interger value
         dynamic Name ="Ram Kumar";      // same data type store string value. 
         dynamic o = obj;                // class's Object stored in dynamic 

What is a CLR?

CLR is Common Language Runtime. If we say that it forms the heart of the .NET Framework, then that will not be wrong. All Languages have their own runtime and this runtime take care of all code execution. As .NET has CLR similarly all other languages are also having their own Runtime like Java has Java Virtual Machine and VC++ has MSCRT40.DLL etc.

For more details, please check our complete article on CLR.

What are the various types of classes in C#?

  • Instance class: It is normal class whose object can be created. Using object, we can access it methods. It is most common class used by developers.
  • Static class: We cannot create object of this class and its methods will be accessible using class name.  
  • Abstract class:  Always act as a base class and other classes inherit it. It is used to force derived class to implement its all abstract methods and helps in keep the same structure in all derived classes.
  • Partial class: provides a special ability to implement the functionality of a single class into multiple files. All the multiple files are combined together at the time of compilation.
  • Sealed class: is used to secure your class and it cannot be inherited. Whenever required we can create an object of Sealed class and use its method. 

Can we use pointers in C#?

Yes, we can use pointer in C#.  A C# pointer is nothing but a variable that holds the memory address of another type. The Pointers in C# statements can be executed in an unsafe context. The statements marked as unsafe by using the unsafe keyword and this piece of code will run outside the control of Garbage Collector.

For more detail, please check out complete article on pointers HERE

public class Program
        static unsafe void Main(string[] args)
            int w = 76;
            int* ptr = &w;

You may also like reading following article on Pointers.

Can we use Multiple Catch Blocks in C#?

Yes, we can use multiple catch block in C#.

In general, the catch block is executed within the order in which they are written in the program. If the given type of exception is matched with the first catch block, then first catch block executes and the remaining of the catch blocks are ignored. And if the starting catch block is not suitable for the exception type, then compiler search for the next catch block until it gets desired CATCH block.

For more detail, please check out complete article HERE.

What is the use of finally block?

‘Finally,’ is a reserved keyword in C#. It is a block of statements that are always executed, regardless of any exceptions that occur in an application. It is used optionally with the “try/catch/finally” or “try/finally” block and guarantees the execution of any code that must be executed before exiting the “try” block, regardless of the success or failure of the application’s execution.

For more details, on finally block in C# please check out complete article HERE

Can try block be nested in C#?

Yes, nesting of the try-catch block is allowed in C#. The nesting of try-block means one try block can be nested into another try block. The various programmer uses the outer try block to handling major exceptions, whereas the inner try block for handling normal or minor exceptions. My personal opinion is that nesting of try-catch reduces the readability of the program so we should use is where it is highly required.

For more details, on finally block in C# please check out complete article HERE

Can we use try without catch C#?

Yes, but we need to use it with finally, like try-finally but if any error occurred in Try that will not get handled and will be moved to outer block catch or to parent method.


      // your try block code will come here.
       // finally block code will come here.

What is Private Constructor in C#?

Private constructor is a special type of constructor which is used in singleton design pattern. It make the class secure and avoid the creation of object of this class.

Below are few important points of private constructor.

  • Private constructor is a special constructor which is used in a class to assign the value to private “readonly” variable.
  • The main purpose of creating private constructor is to restrict the class from being instantiated. When you’ll try to create object, you’ll see the error as “Class is inaccessible due to its protection level”.

For more details on Private Constructors in C#, please check out complete article HERE

Where can we use private constructor?

You can use private constructor in following scenario:

  • It can be used when you want to stop a class to be inherited
  • It is used to stop instantiation of class. (Object cannot be created)
  • It is used in singleton design patterns so that only one instance of a class can be created.
  • Private Constructor is used to assign the value to Private readonly variable like
# Interview Questions

Can we create object of class having private constructor?

No, it’s object cannot be created. You will get compile time error that it is inaccessible due to its protection level.

# Interview Questions

How to get instance of class having Private Constructor?

By using “Activator Class” you can create the object of class having private constructor. Please check below code which will explain how to use “Activator class”.

# Interview Questions

Please check out our “YouTube” video for more detail of Activator class HERE.    

What is Static Constructor in C#?

A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created.

Key points of Static Constructor

  • Static constructor cannot have any access modifier like public/private etc.
  • It cannot have any input parameter.
  • It is invoked implicitly. It can’t be called explicitly.
  • The static constructor for a class executes before any instance of the class is created.

For more details on Static Constructors in C#, please check out complete article HERE

What is abstract Class in C#?

We can create an abstract class by decorating it with abstract keyword. Data abstraction is the process of hiding certain details and showing only essential information to the end user. This abstraction can be achieved with the help of abstract classes.

You can check more on Abstract Class HERE.

Key points of abstract class

  • Abstract class always act a base class and is inherited by other classes.
  • One cannot create an object of abstract class.
  • It can never be static.
  • It can have constructors & destructors.

Where can we use abstract class?

In nutshell we can say that an abstract class is used to provide a base for subclasses. It forces client class to use the same structure.

For example, let’s say we have 4 abstract methods in our abstract class and client class/ sub class must have to implement all these 4 methods, it will give same pattern to our multiple client classes, and this is for what abstract class is known.

For more details on abstract class in C#, please check out complete article HERE

What is Extension method in C#?

Extension methods were introduced in C# 3.0 and used to extend the functionality of a class or type. Extension methods are always created as static methods and also created in Static class. These are basically used to extend the functionality of class or type without making any change in your actual class.

Check detailed article on Extension methods HERE

What are Generics in C#?

Generic means the general form, not anything specific. In C#, generic means not specific to any particular data type. The concept of generics is used to create general-purpose classes, method and types, but type is decided by the compiler at the time of compilation.

Check detailed article on Generics in C# HERE

What are the differences between ref and out keywords?

Both ref and out keywords in C# are used for passing arguments to methods by reference. This will allow changes to the argument within the method to affect the original variable. However, there are a few key differences between these two:

When using the ref keyword, the variable needs to be initialized before it is passed. When using the out keyword, the variable does not have to be initialized before passing to the method.
It suggests that the method will read from and write to the variable.While using out the method must assign a value to the out parameter before the method returns. It suggests that the method is expected to output through this parameter.
When “ref” keyword data may pass in bi-directional.With “out” keyword data can only passed in unidirectional.

What is JIT?

The JIT is known as ‘Just-in-Time’ compiler. It is the component of CLR and is mainly responsible for converting ‘MSIL’ code into ‘Native’ Code. ‘Native’ code is machine dependent code and runs on that machine only where it is created.
JIT is of three types as:

  • PRE JIT compiler–> It’ll compile whole code into ‘Native code’ in single go.
  • ECO JIT complier–> compile only specific methods called at runtime.
  • Normal JIT compiler–> compile the specific code called at runtime and add it in CACHE.

You must read similar .NET Framework Questions HERE

What is the difference between Web Farm and Web Garden?

Web Form:

Whenever your website is having huge amount of incoming traffic and your single server is not enough to handle that large traffic then we use multiple servers and deploy the copy of application on all servers, say I have used 4 servers and all servers will have one copy of application on it. All client requests will come to “LOAD BALANCER” and it will route the request to the appropriate server so that I can be served faster. Load balancers check shortest path, CPU usage and decide when server can server faster and route the request to that server only for faster response back.

Web Garden:

Before explaining web garden I assume you have good understanding of Application Pool.  Application pool have multiple settings and in current scenario we’ll increase the number of worker process (WPW3.exe) allocated to the application pool assigned to your web site. This can definitely boost the performance but finally it also depends upon the Application server hardware too.

You can check more on Application pool worker process HERE.

What is Dispose method in .NET?

In Dot net we have “Finalize” method using which we can clean up our resources. Relying on this is not always good so the best is to implement “Idisposable” interface and implement the “Dispose” method and you can sue it where you want. You can make a call to “dispose” whenever required. Purpose of both is same to release the occupied resources. 

Can we have different access modifiers on get/set methods of a property?

No, we cannot create different modifiers on same property. The access modifier on a property applies to both section i.e.  “get “and “set”. We can create a property with either “get” or “set” but access modifier can be only one for one property.

What are multiple C# statements which break the execution?

Following keywords used to break the execution in C#

  • break
  • goto
  • return

If we write goto, break or return in try block, does finally will execute?

Yes, finally block always runs irrespective of any execution termination statement. Even if any error occurs in try or catch or you forcefully throw the error, in all cases finally block will execute. You cannot make it stop from executing in any case.

What is the difference between String and StringBuilder classes?

String is immutable every time you will concatenate some text in it a new object will be created and stored on new memory address. So, use of string consumes more memory.

StringBuilder is more memory effective if you’ll concatenate any text, it will get stored in its actual object. Unlike string no new object will be created. Hence, it is best practices to use StringBuilder rather than String.

What is the difference between “Web.config” and “Machine.Config”?

“Web.config” setting are applicable to only one application in which it is lying where as “Machine.conifg” settings are applicable to all web application hosted on that machine.  “Web.config” can be multiple but one machine can have only one “Machine.config”.

What is impersonation in ASP.NET?

By default, web application runs under the security context of user which is logged in on the server. In some cases, we need special permission to run web application and perform its task, in that case we use impersonation an application run under the security context of some other user which is having high privileges. This setting can be done in “Web.config”.

Does session use cookies internally?

Yes, session use cookies internally. Although session is stored on server in worker process but its session id is stored in client cookies. When next request is made by client same cookie id is send in request and  if  this cookie id match with id  on server  then server will return session data else session expire message will be returned to the user.

You may have notice that when we clear browser cookie on our machine, on next request we are not sending correct (from cookie) session id (because it is cleared) to server and server will say “session expire” although session data is yet present on server. This is because we are not having correct session id in our cookie to get that session data from server.

I hope, using above list of C#.NET questions we have done valuable add on to your knowledge bank. For more such article you can visit our C# section.                      

Leave a Reply

Your email address will not be published. Required fields are marked *