Practice
Resources
Contests
Online IDE
New
Free Mock
Events New Scaler
Practice
Improve your coding skills with our resources
Contests
Compete in popular contests with top coders
logo
Events
Attend free live masterclass hosted by top tech professionals
New
Scaler
Explore Offerings by SCALER
exit-intent-icon

Download Interview guide PDF

Before you leave, take this C# Interview Questions interview guide with you.
Get a Free Personalized Career Roadmap
Answer 4 simple questions about you and get a path to a lucrative career
expand-icon Expand in New Tab
/ Interview Guides / C# Interview Questions

C# Interview Questions

Last Updated: Feb 23, 2026

Download PDF


Your requested download is ready!
Click here to download.
Certificate included
About the Speaker
What will you Learn?
Register Now
ai interview ai interview

What is C#?

C sharp is an object-oriented programming language developed by Microsoft. C# is used with the .NET framework for creating websites, applications, and games. C# has a varied reasons for being popular:

  • Comparatively easier: Starting with C# is termed comparatively easier than other programming languages
  • Wider use of development: Using C#, you are prone to create web applications or gaming apps. C# has some fantastic features like automatic garbage collection, interfaces, etc. which help build better applications.
  • Larger target audience: Collaboration with Microsoft provides an edge to the applications created using C# since it would have a wider target audience.

Since C# is such a widely used programming language, a plethora of big and small organizations base their products using it. So, prepare yourself with basic and advanced level C# questions to ace the interviews. 

Let’s look at the following comprehensive set of C# Interview Questions and Answers which have been categorised below:

C# Interview Questions for Freshers

1. What is Common Language Runtime (CLR)?

CLR handles program execution for various languages including C#. The architecture of CLR handles memory management, garbage collection, security handling, and looks like: 

Architecture of CLR
Create a free personalised study plan Create a FREE custom study plan
Get into your dream companies with expert guidance
Get into your dream companies with expert..
Real-Life Problems
Prep for Target Roles
Custom Plan Duration
Flexible Plans

2. How is C# different from C?

You would always know C being the procedural language while C# is a more object-oriented language. The biggest difference is that C# supports automatic garbage collection by Common Language Runtime (CLR) while C does not. C# primarily needs a .NET framework to execute while C is a platform-agnostic language. 

3. What is garbage collection in C#?

Garbage collection is the process of freeing up memory that is captured by unwanted objects. When you create a class object, automatically some memory space is allocated to the object in the heap memory. Now, after you perform all the actions on the object, the memory space occupied by the object becomes waste. It is necessary to free up memory. Garbage collection happens in three cases:

  • If the occupied memory by the objects exceeds the pre-set threshold value.
  • If the garbage collection method is called
  • If your system has low physical memory
You can download a PDF version of C Sharp Interview Questions.

Download PDF


Your requested download is ready!
Click here to download.

4. What are the types of classes in C#?

Class is an entity that encapsulates all the properties of its objects and instances as a single unit. C# has four types of such classes:

  • Static class: Static class, defined by the keyword ‘static’ does not allow inheritance. Therefore, you cannot create an object for a static class.

Sample code:

static class classname  
{  
  //static data members  
  //static methods  
}
  • Partial class: Partial class, defined by the keyword ‘partial’ allows its members to partially divide or share source (.cs) files.
  • Abstract class: Abstract classes are classes that cannot be instantiated where you cannot create objects. Abstract classes work on the OOPS concept of abstraction. Abstraction helps to extract essential details and hide the unessential ones.
  • Sealed class: Sealed classes are classes that cannot be inherited. Use the keyword sealed to restrict access to users to inherit that class. 
     
sealed class InterviewBit
{
   // data members
   // methods
   .
   .
   .
}

5. What is a managed and unmanaged code?

Managed code lets you run the code on a managed CLR runtime environment in the .NET framework. 
Managed code runs on the managed runtime environment than the operating system itself. 
Benefits: Provides various services like a garbage collector, exception handling, etc. 

Unmanaged code is when the code doesn’t run on CLR, it is an unmanaged code that works outside the .NET framework. 
They don’t provide services of the high-level languages and therefore, run without them. Such an example is C++. 

Learn via our Video Courses

6. What is the difference between an abstract class and an interface?

Let’s dig into the differences between an abstract class and an interface:

  • Abstract classes are classes that cannot be instantiated ie. that cannot create an object. The interface is like an abstract class because all the methods inside the interface are abstract methods.
  • Surprisingly, abstract classes can have both abstract and non-abstract methods but all the methods of an interface are abstract methods.
  • Since abstract classes can have both abstract and non-abstract methods, we need to use the Abstract keyword to declare abstract methods. But in the interface, there is no such need.

An abstract class has constructors while an interface encompasses none. 

Ex.

Abstract class:

public abstract class Shape{
public abstract void draw();
}

Interface:

public interface Paintable{
void paint();
}

7. What are extension methods in C#?

Extension methods help to add new methods to the existing ones. The methods that are added are static. At times, when you want to add methods to an existing class but don’t perceive the right to modify that class or don’t hold the rights, you can create a new static class containing the new methods. Once the extended methods are declared, bind this class with the existing one and see the methods will be added to the existing one.

// C# program to illustrate the concept
// of the extension methods
using System;
 
namespace ExtensionMethod {
static class NewMethodClass {
 
   // Method 4
   public static void M4(this Scaler s)
   {
       Console.WriteLine("Method Name: M4");
   }
 
   // Method 5
   public static void M5(this Scaler s, string str)
   {
       Console.WriteLine(str);
   }
}
 
// Now we create a new class in which
// Scaler class access all the five methods
public class IB {
 
   // Main Method
   public static void Main(string[] args)
   {
       Scaler s = new Scaler();
       s.M1();
       s.M2();
       s.M3();
       s.M4();
       s.M5("Method Name: M5");
   }
}
}

Output:

Method Name: M1

Method Name: M2

Method Name: M3

Method Name: M4

Method Name: M5

Advance your career with   Mock Assessments Refine your coding skills with Mock Assessments
Real-world coding challenges for top company interviews
Real-world coding challenges for top companies
Real-Life Problems
Detailed reports

8. What are Generics in C#?

In C# collections, defining any kind of object is termed okay which compromises C#’s basic rule of type-safety. Therefore, generics were included to type-safe the code by allowing re-use of the data processing algorithms. Generics in C# mean not linked to any specific data type. Generics reduce the load of using boxing, unboxing, and typecasting objects. Generics are always defined inside angular brackets <>. To create a generic class, this syntax is used:

GenericList<float> list1 = new GenericList<float>();
GenericList<Features> list2 = new GenericList<Features>();
GenericList<Struct> list3 = new GenericList<Struct>();

Here, GenericList<float> is a generic class. In each of these instances of GenericList<T>, every occurrence of T in the class is substituted at run time with the type argument. By substituting the T, we have created three different type-safe using the same class. 

9. What is the difference between an Array and ArrayList in C#?

An array is a collection of similar variables clubbed together under one common name. While ArrayList is a collection of objects that can be indexed individually. With ArrayList you can access a number of features like dynamic memory allocation, adding, searching, and sorting items in the ArrayList. 

  • When declaring an array the size of the items is fixed therefore, the memory allocation is fixed. But with ArrayList, it can be increased or decreased dynamically.
  • Array belongs to system.array namespace while ArrayList belongs to the system.collection namespace.
  • All items in an array are of the same datatype while all the items in an ArrayList can be of the same or different data types.
  • While arrays cannot accept null, ArrayList can accept null values.

For ex.:

// C# program to illustrate the ArrayList
using System;
using System.Collections;
 
class IB {
 
   // Main Method
   public static void Main(string[] args)
   {
 
       // Create a list of strings
       ArrayList al = new ArrayList();
       al.Add("Bruno");
       al.Add("Husky");
       al.Add(10);
       al.Add(10.10);
 
       // Iterate list element using foreach loop
       foreach(var names in al)
       {
           Console.WriteLine(names);
       }
   }
}

10. What is inheritance? Does C# support multiple inheritance?

Inheritance means acquiring some of the properties from a master class. 

Multiple Inheritance in C#

Here, class C can inherit properties from Class A and Class B. Here is an example of inheritance: 

// C# program to illustrate
// multiple class inheritance
using System;
using System.Collections;

// Parent class 1
class Scaler {

  // Providing the implementation
  // of features() method
  public void features()
  {

      // Creating ArrayList
      ArrayList My_features= new ArrayList();

      // Adding elements in the
      // My_features ArrayList
      My_features.Add("Abstraction");
      My_features.Add("Encapsulation");
      My_features.Add("Inheritance");

      Console.WriteLine("Features provided by OOPS:");
      foreach(var elements in My_features)
      {
          Console.WriteLine(elements);
      }
  }
}

// Parent class 2
class Scaler2 :Scaler{

  // Providing the implementation
  // of courses() method
  public void languages()
  {

      // Creating ArrayList
      ArrayList My_features = new ArrayList();

      // Adding elements in the
      // My_features ArrayList
      My_features.Add("C++");
      My_features.Add("C#");
      My_features.Add("JScript");
     

      Console.WriteLine("\nLanguages that use OOPS concepts:");
      foreach(var elements in My_features)
      {
          Console.WriteLine(elements);
      }
  }
}

// Child class
class ScalertoScaler : Scaler2 {
}

public class Scaler1 {

  // Main method
  static public void Main()
  {

      // Creating object of ScalertoScaler class
      ScalertoScaler obj = new ScalertoScaler();
      obj.features();
      obj.languages();
  }
}

Also, C# doesn’t support multiple inheritances. 
Instead, you can use interfaces to inherit the properties using the class name in the signature.

11. What are the differences between ref and out keywords?

C# ref keywords pass arguments by reference and not value. To use the ‘ref’ keyword, you need to explicitly mention ‘ref’. 

void Method(ref int refArgument)
{
   refArgument = refArgument + 10;
}
int number = 1;
Method(ref number);
Console.WriteLine(number);
// Output: 11


C# out keywords pass arguments within methods and functions. 
‘out’ keyword is used to pass arguments in a method as a reference to return multiple values. Although it is the same as the ref keyword, the ref keyword needs to be initialised before it is passed. Here, The out and ref keywords are useful when we want to return a value in the same variables that are passed as an argument. 

public static string GetNextFeature(ref int id)  
{  
   string returnText = "Next-" + id.ToString();  
   id += 1;  
   return returnText;  
}  
public static string GetNextFeature(out int id)  
{  
   id = 1;  
   string returnText = "Next-" + id.ToString();  
   return returnText;  
}   

C# Interview Questions for Experienced

1. What is the difference between String and StringBuilder in C#?

The major difference between String and StringBuilder is that String objects are immutable while StringBuilder creates a mutable string of characters. StringBuilder will make the changes to the existing object rather than creating a new object.

StringBuilder simplifies the entire process of making changes to the existing string object. Since the String class is immutable, it is costlier to create a new object every time we need to make a change. So, the StringBuilder class comes into picture which can be evoked using the System.Text namespace.

In case, a string object will not change throughout the entire program, then use String class or else StringBuilder. 

For ex:

string s = string.Empty; 
for (i = 0; i < 1000; i++) 
  { 
    s += i.ToString() + " "; 
  }

Here, you’ll need to create 2001 objects out of which 2000 will be of no use.

The same can be applied using StringBuilder:

StringBuilder sb = new StringBuilder(); 
for (i = 0; i < 1000; i++) 
 { 
   sb.Append(i); sb.Append(' '); 
 }


By using StringBuilder here, you also de-stress the memory allocator.  

2. What is the difference between constant and readonly in C#?

A const keyword in C# is used to declare a constant field throughout the program. That means once a variable has been declared const, its value cannot be changed throughout the program. 

In C#, a constant is a number, string, null reference, or boolean values. 

For ex:

class IB {
 
   // Constant fields
   public const int xvar = 20;
   public const string str = "InterviewBit";
 
   // Main method
   static public void Main()
   {
 
       // Display the value of Constant fields
       Console.WriteLine("The value of xvar: {0}", xvar);
       Console.WriteLine("The value of str: {0}", str);
   }
}
Output:
The value of xvar is 20.
The value of string is Interview Bit

On the other hand, with readonly keyword, you can assign the variable only when it is declared or in a constructor of the same class in which it is declared. 

Ex:

public readonly int xvar1;
   public readonly int yvar2;
 
   // Values of the readonly 
   // variables are assigned
   // Using constructor
   public IB(int b, int c)
   {
 
       xvar1 = b;
       yvar2 = c;
       Console.WriteLine("The value of xvar1 {0}, "+
                       "and yvar2 {1}", xvar1, yvar2);
   }
 
   // Main method
   static public void Main()
   {
     IB obj1 = new IB(50, 60);
   }
}

Output:
The value of xvar1 is 50, and yvar2 is 60

Constants are static by default while readonly should have a value assigned when the constructor is declared. 
Constants can be declared within functions while readonly modifiers can be used with reference types.  

3. What is Reflection in C#?

Reflection in C# extracts metadata from the datatypes during runtime. 

To add reflection in the .NET framework, simply use System.Refelction namespace in your program to retrieve the type which can be anything from:

  • Assembly
  • Module
  • Enum
  • MethodInfo
  • ConstructorInfo
  • MemberInfo
  • ParameterInfo
  • Type
  • FieldInfo
  • EventInfo
  • PropertyInfo

4. What are the different ways in which a method can be Overloaded in C#?

Overloading means when a method has the same name but carries different values to use in a different context. Only the main() method cannot be overloaded.

In order to overload methods in C#, 

  • Change the number of parameters in a method, or
  • Change the order of parameters in a method, or
  • Use different data types for parameters
    In these ways, you can overload a method multiple times.

For ex.

public class Area {
   public double area(double x) {
       double area = x * x;
       return area;
   }
   public double area(double a, double b) {
       double area = a * b;
       return area;
   }
}

Here, the method Area is used twice. In the first declaration, one argument is used while in the second one, there were two arguments are used. Using different parameters in the same method, we were able to overload the method area().

5. Difference between the Equality Operator (==) and Equals() Method in C#?

Although both are used to compare two objects by value, still they both are used differently. 

For ex.:

int x = 10;
int y = 10;
Console.WriteLine( x == y);
Console.WriteLine(x.Equals(y));
Output:
True
True

Equality operator (==) is a reference type which means that if equality operator is used, it will return true only if both the references point to the same object.  

Equals() method: Equals method is used to compare the values carried by the objects. int x=10, int y=10. If x==y is compared then, the values carried by x and y are compared which is equal and therefore they return true. 

Equality operator: Compares by reference

Equals(): Compares by value 

6. What are Indexers in C#?

Indexers are called smart arrays that allow access to a member variable. Indexers allow member variables using the features of an array. They are created using the Indexer keyword. Indexers are not static members. 

For ex. Here the indexer is defined the same way.

<return type> this[<parameter type> index]
{
   get{
       // return the value from the specified index of an internal collection
   }
   set{
       // set values at the specified index in an internal collection
   }
}

7. What are the Arrays in C#?

When a group of similar elements is clubbed together under one name, they are called arrays. 

For ex. An array of tea Atea[4]: [green tea, chamomile tea, black tea, lemon tea]. The length of the array defines how many elements are present in the array. 

In C#, the memory allocations for the elements of the array happen dynamically.  This is how values are stored in an array sequentially.

Arrays in C#

A few pointers for arrays in C#:

  • The memory allocation is DYNAMIC.
  • Arrays in C# are treated as objects.
  • The length of the array is easy to find by detecting the number of members in the array.
  • The members in the array are ordered and begin with the index value=0.
  • The array types are reference types derived from the base array type.

Syntax: < Data Type > [ ] < Name_Array >

8. What is the difference between late binding and early binding in C#?

Late binding and early binding are examples of one of the primary concepts of OOPS: Polymorphism. 

For ex: one function calculateBill() will calculate bills of premium customers, basic customers, and semi-premium customers based on their policies differently. The calculation for all the customer objects is done differently using the same function which is called polymorphism. 

When an object is assigned to an object variable in C#, the .NET framework performs the binding. 

When the binding function happens at compile-time, it is called early binding. It investigates and checks the methods and properties of the static objects. With early binding, the number of run-time errors decreases substantially and it executes pretty quickly. 

But when the binding happens at runtime, it is called late binding. Late binding happens when the objects are dynamic (decided based on the data they hold) at run-time. It is slower as it looks through during run-time.

9. What are Properties in C#?

Properties in C# are public members of a class where they provide the ability to access private members of a class. The basic principle of encapsulation lets you hide some sensitive properties from the users by making the variables private. The private members are not accessible otherwise in a class. Therefore, by using properties in C# you can easily access the private members and set their values. 

The values can be easily assigned using get and set methods, also known as accessors. While the get method extracts the value, the set method assigns the value to the variables. 

10. What are partial classes in C#?

Partial classes implement the functionality of a single class into multiple files. These multiple files are combined into one during compile time. The partial class can be created using the partial keyword. 

public partial Clas_name  
{
       // code
}

You can easily split the functionalities of methods, interfaces, or structures into multiple files. You can even add nested partial classes. 

11. What is Boxing and Unboxing in C#?

The two functions are used for typecasting the data types:

Boxing: Boxing converts value type (int, char, etc.) to reference type (object) which is an implicit conversion process using object value. 

Example:

int num = 23; // 23 will assigned to num
Object Obj = num; // Boxing

Unboxing: Unboxing converts reference type (object) to value type (int, char, etc.) using an explicit conversion process. 

Example:

int num = 23;         // value type is int and assigned value 23
Object Obj = num;    // Boxing
int i = (int)Obj;    // Unboxing

C# Coding Problems

1. Write a C# program to find if a positive integer is prime or not?

 static void Main(string[] args) 
{ 
    if (FindPrime(47)) 
    { 
        Console.WriteLine("Prime"); 
    } 
    else 
    { 
        Console.WriteLine("Not Prime"); 
    } 
    Console.ReadLine(); 
}   
internal static bool FindPrime(int number) 
{ 
    if (number == 1) return false; 
    if (number == 2) return true; 
    if (number % 2 == 0) return false; 
     var squareRoot = (int)Math.Floor(Math.Sqrt(number)); 
     for (int i = 3; i <= squareRoot; i += 2) 
    { 
        if (number % i == 0) return false; 
    } 
     return true; 
}

2. Write a C# program to find the substring from a given string.

internal static void findallsubstring(string str) 
{ 
   for (int i = 0; i < str.Length; ++i) 
   { 
       StringBuilder subString = new StringBuilder(str.Length - i); 
       for (int j = i; j < str.Length; ++j) 
       { 
           subString.Append(str[j]); 
           Console.Write(subString + " "); 
       } 
   } 
}

3. Write a program in C# Sharp to find if a given string is palindrome or not?

internal static void chkPalindrome(string str) 
{ 
   bool flag = false; 
   for (int i = 0, j = str.Length - 1; i < str.Length / 2; i++, j--) 
   { 
       if (str[i] != str[j]) 
       { 
           flag = false; 
           break; 
       } 
       else 
           flag = true; 
   } 
   if (flag) 
   { 
       Console.WriteLine("Palindrome"); 
   } 
   else 
       Console.WriteLine("Not Palindrome");

Output: 

Input: Key Output: Not Palindrome
Input: step on no pets Output: Palindrome 

4. Write a program in C# Sharp to reverse the order of the given words?

internal static void ReverseWordOrder(string str) 
{ 
  int i; 
  StringBuilder reverseSentence = new StringBuilder(); 
   int Start = str.Length - 1; 
  int End = str.Length - 1; 
   while (Start > 0) 
  { 
      if (str[Start] == ' ') 
      { 
          i = Start + 1; 
          while (i <= End) 
          { 
              reverseSentence.Append(str[i]); 
              i++; 
          } 
          reverseSentence.Append(' '); 
          End = Start - 1; 
      } 
      Start--; 
  } 
   for (i = 0; i <= End; i++) 
  { 
      reverseSentence.Append(str[i]); 
  } 
  Console.WriteLine(reverseSentence.ToString()); 
}

5. Write a program in C# Sharp to reverse a string?

internal static void ReverseString(string str) 
{ 
   
  char[] charArray = str.ToCharArray(); 
  for (int i = 0, j = str.Length - 1; i < j; i++, j--) 
  { 
      charArray[i] = str[j]; 
      charArray[j] = str[i]; 
  } 
  string reversedstring = new string(charArray); 
  Console.WriteLine(reversedstring); 

C#.NET Interview Questions

1. What is the difference between IEnumerable, ICollection, and IList in C#?

These are collection interfaces in C# with increasing functionality.

IEnumerable is the base interface. It allows forward-only iteration using foreach. It does not support adding, removing, or indexing elements. It is used when you only need to read data.

ICollection extends IEnumerable. It adds methods like Add, Remove, Clear, and the Count property. It allows modification of the collection.

IList extends ICollection. It adds index-based access using an integer index. It allows inserting or removing items at specific positions.

The key difference is capability:

  • IEnumerable supports iteration only.
  • ICollection supports modification and counting.
  • IList supports indexing in addition to modification.

In interviews, mention the principle of least-specific interface. When defining method parameters, use the most general interface required. For example, use IEnumerable if the method only reads data. This improves flexibility and reduces coupling.


 

2. What is middleware in ASP.NET Core? How does the request pipeline work?

Middleware in ASP.NET Core are components that handle HTTP requests and responses. They are arranged in a pipeline. Each middleware can process the request, pass it to the next component, and then process the response on the way back.

The order of middleware registration matters because execution follows the order in Program.cs or Startup configuration.

Example:

app.UseRouting();

app.UseAuthentication();

app.UseAuthorization();

app.MapControllers();

When a request comes in:

  1. The first middleware processes it.

     
  2. It calls the next middleware.

     
  3. The request continues through the pipeline.

     
  4. The response travels back through the same middleware in reverse order.

     

Custom middleware is created using a class that accepts a RequestDelegate.

Example:

public class CustomMiddleware
{
   private readonly RequestDelegate _next;


   public CustomMiddleware(RequestDelegate next)
   {
       _next = next;
   }

   public async Task InvokeAsync(HttpContext context)
   {
       await _next(context);
   }
}

You should explain that middleware controls cross-cutting concerns such as authentication, logging, error handling, and routing.


 

3. What is Entity Framework? Explain Code-First vs Database-First.

Entity Framework (EF) is an Object-Relational Mapper (ORM) in .NET. It allows developers to work with databases using C# objects instead of writing raw SQL queries.

Instead of manually mapping tables and columns, EF maps database tables to C# classes and rows to objects. This reduces boilerplate code and improves productivity.

The core components of Entity Framework are:

DbContext is the main class that manages the database connection and tracks changes to entities.

DbSet represents a table in the database. Each DbSet<T> maps to a table.

Example:

public class AppDbContext : DbContext
{
   public DbSet<Student> Students { get; set; }
}

Code-First approach means you first create C# classes (models), and then Entity Framework generates the database schema from those models. Migrations are used to update the database when models change. This approach is common in new projects because it keeps the domain model as the source of truth.

Database-First approach means you start with an existing database. EF generates C# models based on the database schema. This is useful when working with legacy databases.

Another important concept is loading related data:

Lazy loading loads related data automatically when accessed, but it can cause multiple database calls.

Eager loading uses Include() to load related data in a single query, which improves performance.

In interviews, you should explain that EF simplifies database interaction and supports LINQ queries directly on DbSet.

4. Explain async and await in C#. What is the difference between Task and Thread?

The async and await keywords allow asynchronous programming in C#. They help run long operations without blocking the calling thread.

When a method is marked as async, it can use await to pause execution until a Task completes. During this waiting period, the thread is released back to the thread pool instead of being blocked.


Example:

public async Task<string> GetDataAsync()
{
   return await httpClient.GetStringAsync("url");
}

A Task represents an ongoing or future operation. It is a higher-level abstraction for asynchronous work. Tasks usually run on the ThreadPool and are lightweight compared to manually created threads.

A Thread is an operating system-level execution unit. It is heavier, consumes more resources, and requires manual management.

Key differences:

  • Task is managed by the .NET runtime.
  • Thread is managed at OS level.
  • Task is preferred for asynchronous I/O operations.
  • Thread is used for low-level concurrency control.

Important interview points include avoiding async void except for event handlers, using async Task instead, and avoiding blocking calls like .Result or .Wait() because they can cause deadlocks.

 

ConfigureAwait(false) is often used in library code to prevent capturing the synchronization context, which improves performance and avoids UI deadlocks.

In interviews, clearly explain that async/await improves scalability by freeing threads during I/O waits instead of creating new threads.


 

5. What is LINQ in C#? Explain query syntax vs method syntax.

LINQ stands for Language Integrated Query. It allows developers to query collections, databases, XML, and other data sources using a consistent syntax inside C#.

Before LINQ, developers had to use loops for collections and SQL for databases. LINQ provides a unified querying approach.

Query syntax looks similar to SQL:

var result = from s in students
            where s.Marks > 80
            select s;

Method syntax uses extension methods and lambda expressions:

var result = students.Where(s => s.Marks > 80);

Internally, both syntaxes compile into the same Intermediate Language. The compiler converts query syntax into method syntax.

LINQ uses deferred execution by default. This means the query does not execute when defined. It runs only when the result is iterated or converted using methods like ToList().

Another important difference is between IEnumerable and IQueryable. IEnumerable executes in memory and is used for collections. IQueryable builds expression trees and translates queries into SQL when used with databases such as Entity Framework.

In interviews, mention that method syntax is more flexible and commonly used in production code.


 

6. What are delegates in C#? How are they different from events?

A delegate is a type-safe reference to a method. It defines a method signature and can store a reference to any method that matches that signature. It works like a function pointer, but with type safety.

Example:

public delegate void Notify(string message);

  • Delegates are commonly used for callbacks, event handling, and passing methods as parameters. A delegate can reference more than one method at a time. This is called a multicast delegate. When invoked, all attached methods execute in order.
  • An event is built on top of a delegate. It provides an additional layer of protection. External classes can subscribe or unsubscribe to an event, but they cannot invoke it directly. Only the class that declares the event can raise it.
  • This is the main difference. A delegate can be invoked from anywhere it is accessible. An event restricts invocation to the declaring class, which protects the internal logic.
  • In applications, events follow the EventHandler pattern and are used in UI programming and publisher-subscriber models.



 

7. What is the difference between .NET Framework, .NET Core, and .NET 5+ (Unified .NET)?

.NET Framework is the original implementation of .NET. It runs only on Windows and is used for older applications such as ASP.NET (classic), Windows Forms, and WPF. It is installed system-wide and does not support easy side-by-side versioning. It is now in maintenance mode, which means it receives security updates but no major new features.

.NET Core was introduced to support cross-platform development. It runs on Windows, Linux, and macOS. It is modular and lightweight. It supports side-by-side installation, so different applications can use different runtime versions without conflict. It was built for modern workloads such as cloud applications, microservices, and containerized environments.

Starting from .NET 5, Microsoft unified .NET Core into a single platform called .NET. .NET 6, 7, and 8 continue this unified model. .NET 8 is the current Long-Term Support version. This unified platform supports web applications, desktop apps, cloud services, mobile development (via MAUI), and APIs under one runtime.

Performance is generally better in .NET Core and later versions due to runtime optimizations and improved garbage collection. Modern .NET also supports flexible deployment models such as framework-dependent deployment, self-contained deployment, and container-based deployment.

For interviews, the key point is: new development should use .NET 6 or later. .NET Framework is mainly used to maintain legacy systems.


 

C# OOPs Interview Questions

1. What are constructors and destructors in C#? Explain constructor chaining.

A constructor is a special method used to initialize an object when it is created. It has the same name as the class and does not have a return type.

C# supports different types of constructors:

  • A default constructor has no parameters.
  • A parameterized constructor accepts arguments.
  • A static constructor initializes static members of a class.
  • A copy constructor creates a new object from another object (implemented manually in C#).

Example:

public class Person
{
   public string Name;

   public Person(string name)
   {
       Name = name;
   }
}
Constructor chaining allows one constructor to call another constructor within the same class using this().

Example:

public class Person
{
   public string Name;
   public int Age;

   public Person(string name) : this(name, 0)
   {
   }

   public Person(string name, int age)
   {
       Name = name;
       Age = age;
   }
}

You can also call a base class constructor using base().

Static constructors are used to initialize static fields. They run only once per type and are thread-safe by default.

A destructor is defined using a tilde:
~Person()
{
}

However, destructors are called by the Garbage Collector and should rarely be used. Instead, C# uses the IDisposable pattern and the using statement for releasing unmanaged resources.


 

2. What are all six access modifiers in C#? Explain each.

C# provides six access modifiers to control visibility.

  1. public means the member is accessible from anywhere.
  2. private means the member is accessible only within the same class.
  3. protected means the member is accessible within the same class and in derived classes.
  4. internal means the member is accessible within the same assembly.
  5. protected internal means the member is accessible either from the same assembly or from derived classes in another assembly.
  6. private protected means the member is accessible only within the same assembly and only in derived classes. This modifier was introduced in C# 7.2.

Default access levels are important. If no modifier is specified:

  • Top-level classes are internal by default.
  • Class members are private by default.

In interviews, clearly explain the difference between protected internal and private protected, because that distinction is commonly tested.

3. What is the difference between composition and inheritance? When should you prefer composition?

Inheritance represents an "is-a" relationship. A Dog is an Animal. The derived class inherits properties and behavior from the base class.

Composition represents a "has-a" relationship. A Car has an Engine. Instead of inheriting behavior, the class contains an instance of another class.

Example of inheritance:

public class Animal
{
   public void Eat() { }
}

public class Dog : Animal
{
}
Example of composition:
public class Engine
{
   public void Start() { }
}

public class Car
{
   private Engine _engine = new Engine();
}

Inheritance creates tight coupling between base and derived classes. Changes in the base class can affect all derived classes. This is known as the fragile base class problem.

Composition provides more flexibility. You can change behavior by replacing components without modifying the base structure.

In modern design, the principle is: favor composition over inheritance. Use inheritance only when there is a clear and stable is-a relationship. Prefer composition when you need flexibility, loose coupling, and better maintainability.

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

A class is a reference type, while a struct is a value type. This is the most important difference to mention.

Classes are stored on the heap. When you assign a class object to another variable, both variables reference the same memory location. Changes made through one reference affect the same object.

Structs are stored on the stack when declared locally. When you assign a struct to another variable, a copy is created. Changes to one copy do not affect the other.

Classes support inheritance. A class can inherit from another class. Structs cannot inherit from another struct or class, but they can implement interfaces.

Classes can have a parameterless constructor automatically provided by the compiler. Structs always have an implicit default constructor and cannot define their own parameterless constructor (before C# 10; C# 10 allows it with restrictions).

Classes can be null. Structs are not nullable unless wrapped inside Nullable<T> or declared using the ? syntax, such as int?.

Use a struct when:

  • The type is small in size.
  • The object represents a single value.
  • It is immutable.
  • It will be created frequently.

Use a class when:

  • The object is large.
  • It requires inheritance.
  • It represents complex behavior.
  • You need reference semantics.

At the time of interview, you can say that struct is best for small, lightweight data structures like Point or DateTime, while class is used for complex business objects.

 

5. What is method overriding? How does it differ from method hiding (new keyword)?

Method overriding occurs when a derived class provides a new implementation of a method defined in a base class. The base method must be marked as virtual, and the derived method must use override.

Example:

public class Base
{
   public virtual void Show()
   {
       Console.WriteLine("Base");
   }
}

public class Derived : Base
{
   public override void Show()
   {
       Console.WriteLine("Derived");
   }
}

If you create:

Base obj = new Derived();

obj.Show();

The output will be "Derived" because overriding supports runtime polymorphism.

Method hiding uses the new keyword instead of override.

Example:

public class Derived : Base
{
   public new void Show()
   {
       Console.WriteLine("Derived");
   }
}
Now:
Base obj = new Derived();
obj.Show();

The output will be "Base" because the method is hidden, not overridden. The method call depends on the reference type, not the object type.

The key difference is that overriding replaces the base implementation in the virtual method table, while hiding creates a separate method. Overriding supports runtime polymorphism. Hiding does not.


 

6. Explain compile-time vs runtime polymorphism in C# with examples.

Polymorphism allows objects to behave differently using the same method name. It can occur at compile time or runtime.

Compile-time polymorphism is resolved during compilation. It is achieved through method overloading or operator overloading. The compiler decides which method to call based on parameters.

Example:
public class Calculator
{
   public int Add(int a, int b)
   {
       return a + b;
   }

   public double Add(double a, double b)
   {
       return a + b;
   }
}

The method called is determined at compile time based on argument types.

Runtime polymorphism is resolved at runtime. It is achieved through method overriding using virtual and override keywords.

Example:

public class Animal
{
   public virtual void Speak()
   {
       Console.WriteLine("Animal sound");
   }
}


public class Dog : Animal
{
   public override void Speak()
   {
       Console.WriteLine("Bark");
   }
}

If an Animal reference points to a Dog object, the Dog’s Speak() method is called. This decision happens at runtime using a virtual method table.

Don’t forget to explain that compile-time polymorphism increases flexibility through method signatures, while runtime polymorphism enables dynamic behavior based on object type.


 

7. What is encapsulation in C#? How do you implement it using access modifiers?

Encapsulation is the practice of hiding internal data and allowing controlled access through methods or properties. It ensures that object data cannot be modified directly in an unsafe way.

In C#, encapsulation is implemented using access modifiers such as private, protected, and public.

A common pattern is to keep fields private and expose them using properties.

Example:

public class Employee

{
   private decimal salary;

   public decimal Salary
   {
       get { return salary; }
       set
       {
           if (value > 0)
               salary = value;
       }
   }
}

Here, salary cannot be accessed directly. The property enforces validation.

Modern C# also supports auto-properties:

public string Name { get; set; }

And init-only setters introduced in C# 9:

public string Name { get; init; }

Init-only properties allow setting values only during object initialization, improving immutability.

Encapsulation follows the principle of least privilege. Members should be as restricted as possible and only exposed when necessary.

While explaining, emphasize that encapsulation protects object integrity and prevents invalid state changes.
 

8. What are the four pillars of OOP in C#? Explain with real-world examples.

The four pillars of Object-Oriented Programming in C# are Encapsulation, Inheritance, Polymorphism, and Abstraction. Together, they help structure code in a modular, reusable, and maintainable way.

Encapsulation means bundling data and methods into a single unit, usually a class, and restricting direct access to internal data. For example, a bank account class hides the balance field and exposes methods like Deposit() and Withdraw(). Users cannot directly change the balance without rules being applied.

Inheritance allows one class to reuse code from another class. A derived class inherits properties and methods from a base class. For example, a Vehicle base class may contain StartEngine(), and a Car class inherits it instead of rewriting it.

Polymorphism allows one interface to represent different underlying forms. For example, a Shape class may define a Draw() method. A Circle and Rectangle both override Draw() in their own way. The same method call behaves differently depending on the object type.

Abstraction means exposing only essential features and hiding internal complexity. A car dashboard shows speed and fuel level but hides engine mechanics. Similarly, in C#, abstract classes and interfaces expose behavior without revealing implementation details.


 

Design Patterns Interview Questions C#

1. What are design patterns? How are they classified (Creational, Structural, Behavioral)?

 


Design patterns are reusable solutions to common software design problems. They are not ready-made code, but proven approaches that help structure code in a clean and maintainable way.

Design patterns are classified into three main categories.

Creational patterns focus on object creation. They control how objects are created and instantiated. Examples include Singleton, Factory, Builder, and Prototype.

Example of a creational pattern in C#:

public class Logger
{
   private static readonly Logger _instance = new Logger();
   private Logger() { }
   public static Logger Instance => _instance;
}

Structural patterns focus on how classes and objects are composed to form larger structures. They help organize relationships between objects. Examples include Adapter, Decorator, Facade, and Proxy.

Example of a structural pattern:

public interface ITarget
{
   void Request();
}

public class Adapter : ITarget
{
   private readonly Adaptee _adaptee = new Adaptee();
   public void Request()
   {
       _adaptee.SpecificRequest();
   }
}

Behavioral patterns focus on communication between objects and how responsibilities are distributed. Examples include Observer, Strategy, Command, and Iterator.

Example of a behavioral pattern:

public interface IStrategy
{
   int Execute(int a, int b);
}

public class AddStrategy : IStrategy
{
   public int Execute(int a, int b) => a + b;
}

Always remember that creational patterns manage object creation, structural patterns manage composition, and behavioral patterns manage communication.


 

2. Implement the Singleton pattern in C# with thread safety. What are its drawbacks?

The Singleton pattern ensures that a class has only one instance and provides a global access point to it.

Thread-safe implementation using Lazy<T> (recommended):

public sealed class Singleton
{
   private static readonly Lazy<Singleton> _instance =
       new Lazy<Singleton>(() => new Singleton());


   public static Singleton Instance => _instance.Value;

   private Singleton() { }
}
Lazy<T> ensures thread safety and lazy initialization without manual locking.
Thread-safe implementation using lock:
public sealed class Singleton
{
   private static Singleton _instance;
   private static readonly object _lock = new object();


   public static Singleton Instance
   {
       get
       {
           lock (_lock)
           {
               if (_instance == null)
                   _instance = new Singleton();
               return _instance;
           }
       }
   }


   private Singleton() { }
}
Static initialization approach:
public sealed class Singleton
{
   private static readonly Singleton _instance = new Singleton();
   public static Singleton Instance => _instance;
   private Singleton() { }
}

Drawbacks of Singleton:

It introduces global state.
It creates tight coupling.
It makes unit testing difficult.
It violates Dependency Inversion in many cases.

In modern .NET applications, dependency injection is preferred over Singleton for managing object lifetimes.


 

3. What is the Factory Method pattern? Implement it in C# with an example.

The Factory Method pattern defines an interface for creating objects, but lets subclasses decide which object to instantiate.

Instead of directly calling new, object creation is delegated to a factory.

Example:

public interface IVehicle
{
   void Drive();
}

public class Car : IVehicle
{
   public void Drive() => Console.WriteLine("Car driving");
}


public class Bike : IVehicle
{
   public void Drive() => Console.WriteLine("Bike riding");
}


public interface IVehicleFactory
{
   IVehicle CreateVehicle();
}


public class CarFactory : IVehicleFactory
{
   public IVehicle CreateVehicle() => new Car();
}


public class BikeFactory : IVehicleFactory
{
   public IVehicle CreateVehicle() => new Bike();
}

The client depends on the IVehicle interface, not on concrete classes.

Difference from Simple Factory: A simple factory uses a single method with conditions to create objects. Factory Method uses subclasses to decide the type, which follows the Open/Closed Principle.

Use Factory Method when object creation logic is complex or needs to vary based on context.


 

4. What are SOLID principles? Explain each with a C# example.

SOLID is a set of five design principles that improve maintainability and flexibility in object-oriented systems.

Single Responsibility Principle means a class should have only one reason to change.

Violation:

public class Report

{
   public void Generate() { }
   public void SaveToFile() { }
}
Better design separates responsibilities:
public class ReportGenerator
{
   public void Generate() { }
}

public class ReportSaver
{
   public void SaveToFile() { }
}

Open/Closed Principle means classes should be open for extension but closed for modification.

Instead of modifying a class for new behavior, extend it using inheritance or interfaces.

Liskov Substitution Principle means a derived class should be replaceable with its base class without breaking behavior.

If a derived class changes expected behavior, it violates LSP.

Interface Segregation Principle means clients should not be forced to depend on methods they do not use.

Instead of one large interface:

public interface IMachine

{
   void Print();
   void Scan();
}
Split into smaller interfaces:
public interface IPrinter
{
   void Print();
}

public interface IScanner
{
   void Scan();
}

Dependency Inversion Principle means high-level modules should depend on abstractions, not concrete implementations.

Violation:

public class OrderService
{
   private readonly SqlRepository _repository = new SqlRepository();
}
Better approach:
public class OrderService
{
   private readonly IRepository _repository;

   public OrderService(IRepository repository)
   {
       _repository = repository;
   }
}

This principle is the foundation of dependency injection.


 

5. What is the Repository pattern? How is it used with Entity Framework in C#?

The Repository pattern abstracts data access logic behind a collection-like interface. Instead of interacting directly with Entity Framework’s DbContext throughout the application, data operations are centralized inside a repository.

The goal is to separate business logic from data access logic.

A typical repository interface looks like this:

public interface IRepository<T>
{
   T GetById(int id);
   IEnumerable<T> GetAll();
   void Add(T entity);
   void Update(T entity);
   void Delete(T entity);
}

An implementation using Entity Framework might look like this:


public class Repository<T> : IRepository<T> where T : class
{
   private readonly DbContext _context;
   private readonly DbSet<T> _dbSet;


   public Repository(DbContext context)
   {
       _context = context;
       _dbSet = context.Set<T>();
   }
   public T GetById(int id) => _dbSet.Find(id);
   public IEnumerable<T> GetAll() => _dbSet.ToList();
   public void Add(T entity) => _dbSet.Add(entity);
   public void Update(T entity) => _dbSet.Update(entity);
   public void Delete(T entity) => _dbSet.Remove(entity);
}

It is often paired with the Unit of Work pattern, where a single DbContext manages transactions across multiple repositories.

There is debate in modern .NET development about whether Repository is necessary when using EF Core, since DbContext already behaves like a repository and unit of work. In simple applications, using DbContext directly may be enough. In larger systems, repositories improve testability and abstraction.

In interviews, you can explain both the purpose and the practical debate. 
 

6. What is Dependency Injection (DI) in C#? Explain the three types of injection.

Dependency Injection means providing dependencies to a class from outside rather than creating them inside the class. This reduces tight coupling and improves testability.

Instead of:

public class OrderService
{
   private readonly SqlRepository _repo = new SqlRepository();
}
You inject the dependency:
public class OrderService
{
   private readonly IRepository _repo;

   public OrderService(IRepository repo)
   {
       _repo = repo;
   }
}

There are three main types of injection.

Constructor injection is the most common and recommended type. Dependencies are passed through the constructor. It ensures that the object cannot exist without required dependencies.

Property injection uses public properties to assign dependencies after object creation. It is less strict and may result in partially initialized objects.

Method injection provides dependencies through method parameters. It is used when the dependency is required only for a specific operation.

In ASP.NET Core, services are registered using:

  • AddTransient creates a new instance every time it is requested.
  • AddScoped creates one instance per HTTP request.
  • AddSingleton creates a single instance for the entire application lifetime.

Choosing the correct service lifetime is important. For example, DbContext is typically registered as Scoped.

Also, don’t forget to explain that DI supports the Dependency Inversion Principle and improves unit testing.


 

7. What is the Observer pattern? How do C# events and delegates implement it?

The Observer pattern defines a one-to-many relationship between objects. When one object changes state, all dependent objects are notified automatically.

In C#, events and delegates provide built-in support for the Observer pattern.

Example:

public class Publisher
{
   public event EventHandler OnChanged;

   public void ChangeState()
   {
       OnChanged?.Invoke(this, EventArgs.Empty);
   }
}


public class Subscriber
{
   public void HandleChange(object sender, EventArgs e)
   {
       Console.WriteLine("State changed");
   }
}

Subscribers attach to the event:

publisher.OnChanged += subscriber.HandleChange;

When the publisher raises the event, all subscribed handlers execute.

C# also provides IObservable<T> and IObserver<T> interfaces for push-based notifications. These are commonly used in reactive programming.

Reactive Extensions (Rx) build on this model and support complex event streams.

8. What is the Strategy pattern? Provide a C# implementation.

The Strategy pattern encapsulates a family of algorithms and makes them interchangeable. Instead of using large if-else or switch statements, behavior is selected at runtime.

Example:

public interface ISortStrategy
{
   void Sort(int[] array);
}

public class BubbleSort : ISortStrategy
{
   public void Sort(int[] array)
   {
       Console.WriteLine("Bubble sorting");
   }
}


public class QuickSort : ISortStrategy
{
   public void Sort(int[] array)
   {
       Console.WriteLine("Quick sorting");
   }
}

public class SortContext
{
   private readonly ISortStrategy _strategy;


   public SortContext(ISortStrategy strategy)
   {
       _strategy = strategy;
   }


   public void Execute(int[] data)
   {
       _strategy.Sort(data);
   }
}

The algorithm can be changed by passing a different strategy implementation.

Strategy eliminates complex conditional logic and follows the Open/Closed Principle.

9. What is the difference between Abstract Factory and Factory Method patterns?

Factory Method defines a single method for creating objects and allows subclasses to decide which class to instantiate. It focuses on creating one type of product.

Abstract Factory creates families of related objects without specifying their concrete classes. It focuses on multiple related products.

Factory Method example:

A base class defines a CreateProduct() method, and subclasses override it to create specific products.

Abstract Factory example:

public interface IUIFactory
{
   IButton CreateButton();
   ICheckbox CreateCheckbox();
}

public class WindowsFactory : IUIFactory
{
   public IButton CreateButton() => new WindowsButton();
   public ICheckbox CreateCheckbox() => new WindowsCheckbox();
}

public class MacFactory : IUIFactory
{
   public IButton CreateButton() => new MacButton();
   public ICheckbox CreateCheckbox() => new MacCheckbox();
}

Here, the factory creates a family of related UI components.

Key difference:

  • Factory Method handles one product.
  • Abstract Factory handles families of related products.
  • Factory Method uses inheritance to defer object creation.
  • Abstract Factory uses composition to provide related objects together.

In interviews, you should clearly explain that Abstract Factory is useful when the system needs to support multiple product families consistently.

C# MCQ

1.

Which reference modifier is used to define reference variables?

2.

What are the types of ‘Data Conversion’ in C#?

3.

What is the process of defining a method in terms of itself, that is a method that calls itself?

4.

What will be the output of the following C# code?

static void Main(string[] args)
{
   int []a = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
   func(ref a);
   Console.ReadLine();
}
static void func(ref int[] x)
{
   Console.Write(" numbers are : ");
   for (int i = 0; i < x.Length; i++)
   {
       if (x[i] % 2 == 0)
       {
           x[i] = x[i] + 1;
           Console.Write(x[i] +" ");
       }
   }
}
5.

What will be the output of the following C# expression?

int  a+= (float) b/= (long)c
6.

What is the subset of ‘int’ datatype?

7.

Which of the following modifiers is used when an abstract method is redefined by a derived class?

8.

What will be the output of the following code?

static void Main(string[] args)
  {
      int x = 4 ,b = 2;
      x -= b/= x * b;
      Console.WriteLine(x + " " + b);
      Console.ReadLine();
  }
9.

The correct way of incrementing the operators are:

10.

What is the need for ‘Conversion of data type’ in C#?

11.

What is the output of this code?

class maths
{
   public int fun(int k, int y)
   {
       return k + y;
   }
   public int fun1(int t, float z)
   {
       return (t+(int)z);
   }
}   
class Program
{
   static void Main(string[] args)
   {
       maths obj = new maths();
       int i;
       int b = 90;
       int c = 100;
       int d = 12;
       float l = 14.78f;
       i = obj.fun(b, c);
       Console.WriteLine(i);
       int j = (obj.fun1(d,  l));
       Console.WriteLine(j);
       Console.ReadLine();
   }
}
12.

What will be the output of the following C# code?

static void Main(string[] args)
{
    int a, b, c, x;
    a = 90;
    b = 15;
    c = 3;
    x = a - b / 3 + c * 2 - 1;
    Console.WriteLine(x);
    Console.ReadLine();
}
Excel at your interview with Masterclasses Know More
Certificate included
What will you Learn?
Free Mock Assessment
Fill up the details for personalised experience.
Phone Number *
OTP will be sent to this number for verification
+91 *
+91
Change Number
Graduation Year *
Graduation Year *
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
*Enter the expected year of graduation if you're student
Current Employer
Company Name
College you graduated from
College/University Name
Job Title
Job Title
Engineering Leadership
Software Development Engineer (Backend)
Software Development Engineer (Frontend)
Software Development Engineer (Full Stack)
Data Scientist
Android Engineer
iOS Engineer
Devops Engineer
Support Engineer
Research Engineer
Engineering Intern
QA Engineer
Co-founder
SDET
Product Manager
Product Designer
Backend Architect
Program Manager
Release Engineer
Security Leadership
Database Administrator
Data Analyst
Data Engineer
Non Coder
Other
Please verify your phone number
Edit
Resend OTP
By clicking on Start Test, I agree to be contacted by Scaler in the future.
Already have an account? Log in
Free Mock Assessment
Instructions from Interviewbit
Start Test