Interview Questions

Get ready for your next interview with our comprehensive question library

C# Interview Questions

Filter by Difficulty

1.

Explain the difference between value types and reference types in C#.

beginner

Value Types:

  • Stored directly in memory (stack for local variables)
  • Hold the actual data
  • Examples: int, bool, char, struct, enum
  • Assignment copies the value
  • Default values are zero/false/null equivalent
    Reference Types:
  • Stored on the heap, variable holds a reference to the memory location
  • Examples: class, string, array, delegate
  • Assignment copies the reference, not the data
  • Default value is null
  • Multiple variables can reference the same object
2.

What is the difference between `const` and `readonly` in C#?

beginner

const:

  • Compile-time constant
  • Must be initialized at declaration
  • Value cannot change
  • Implicitly static
  • Only primitive types, null, or string literals
    readonly:
  • Runtime constant
  • Can be initialized at declaration or in constructor
  • Value can be set once per instance
  • Can be instance or static
  • Can hold any type including complex objects
public class Example
{
    const int MAX_SIZE = 100;           // Compile-time constant
    readonly DateTime createdDate;      // Runtime constant
    public Example()
    {
        createdDate = DateTime.Now;     // Can set in constructor
    }
}
3.

What are namespaces in C# and why are they important?

beginner

Namespaces organize code into logical groups and prevent naming conflicts. They provide a hierarchical organization system for types.
Benefits:

  • Avoid naming collisions
  • Organize related functionality
  • Improve code readability
  • Enable partial type loading
namespace MyCompany.DataAccess
{
    public class DatabaseConnection { }
}
namespace MyCompany.UI
{
    public class DatabaseConnection { } // Same name, different namespace
}
4.

What is the `var` keyword and when should you use it?

beginner

var enables implicit typing where the compiler determines the type from the assigned value. The variable is still strongly typed.
Best Practices:

  • Use when type is obvious from assignment
  • Required for anonymous types
  • Use with LINQ queries for complex return types
  • Avoid when it reduces code readability
var number = 42;           // int
var text = "Hello";        // string
var list = new List<int>(); // List<int>
// Required for anonymous types
var person = new { Name = "John", Age = 30 };
5.

Explain the four pillars of Object-Oriented Programming.

beginner

1. Encapsulation: Bundling data and methods together, hiding internal implementation details.
2. Inheritance: Creating new classes based on existing classes, promoting code reuse.
3. Polymorphism: Objects of different types can be treated as instances of the same type through a common interface.
4. Abstraction: Hiding complex implementation details while showing only essential features.

6.

Explain method overriding vs method overloading.

beginner

Method Overloading:

  • Multiple methods with same name but different parameters
  • Compile-time polymorphism
  • Same class can have overloaded methods
    Method Overriding:
  • Redefining a method in derived class
  • Runtime polymorphism
  • Requires virtual in base class and override in derived class
// Overloading
public class Calculator
{
    public int Add(int a, int b) { return a + b; }
    public double Add(double a, double b) { return a + b; }
}
// Overriding
public class Shape
{
    public virtual double GetArea() { return 0; }
}
public class Circle : Shape
{
    public override double GetArea() { return Math.PI * radius * radius; }
}
7.

Explain access modifiers in C#.

beginner

public: Accessible from anywhere.
private: Accessible only within the same class.
protected: Accessible within the class and its derived classes.
internal: Accessible within the same assembly.
protected internal: Accessible within the same assembly or derived classes.
private protected: Accessible within the same assembly and only in derived classes.

8.

What are constructors and their types in C#?

beginner

Constructors are special methods called when an object is created. They initialize the object's state.
Types:

  • Default Constructor: No parameters, provided by compiler if none defined
  • Parameterized Constructor: Takes parameters for initialization
  • Copy Constructor: Not directly supported, must be implemented manually
  • Static Constructor: Initializes static members, called once per type
  • Private Constructor: Prevents instantiation (often used in singleton pattern)
public class Person
{
    // Parameterized constructor
    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }
    // Static constructor
    static Person()
    {
        // Initialize static members
    }
}
9.

What are nullable types and how do you use them?

beginner

Nullable types allow value types to have null values. Useful for database scenarios where values might be undefined.

int? nullableInt = null;
bool? nullableBool = null;
// Checking for null
if (nullableInt.HasValue)
{
    int value = nullableInt.Value;
}
// Null coalescing operator
int result = nullableInt ?? 0; // Use 0 if null
10.

Explain the difference between `string` and `StringBuilder`.

beginner

string:

  • Immutable - operations create new string objects
  • Good for few string operations
  • Thread-safe (immutability)
    StringBuilder:
  • Mutable - modifies existing buffer
  • Efficient for multiple string operations
  • Not thread-safe
  • Has capacity management
// Inefficient - creates multiple string objects
string result = "";
for (int i = 0; i < 1000; i++)
{
    result += i.ToString(); // Creates new string each time
}
// Efficient - uses internal buffer
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++)
{
    sb.Append(i); // Modifies existing buffer
}
string result = sb.ToString();
11.

Explain implicit and explicit type conversion.

beginner

Implicit Conversion:

  • Automatic conversion by compiler
  • No data loss
  • Smaller to larger types
    Explicit Conversion:
  • Manual conversion using cast operator
  • Potential data loss
  • Larger to smaller types or incompatible types
// Implicit conversion
int intValue = 123;
double doubleValue = intValue; // Automatic conversion
// Explicit conversion
double largeValue = 123.456;
int smallValue = (int)largeValue; // Manual cast, loses decimal part
// Using Convert class
string numberString = "123";
int convertedValue = Convert.ToInt32(numberString);
12.

What is the difference between `Parse()` and `TryParse()` methods?

beginner

Parse():

  • Throws exception if conversion fails
  • Returns converted value directly
  • Use when certain input is valid
    TryParse():
  • Returns boolean indicating success/failure
  • Uses out parameter for converted value
  • Use when input validity is uncertain
// Parse - throws exception on failure
try
{
    int value1 = int.Parse("123");
    int value2 = int.Parse("abc"); // Throws FormatException
}
catch (FormatException ex) { }
// TryParse - safe conversion
if (int.TryParse("123", out int value3))
{
    // Conversion successful
}
else
{
    // Conversion failed, value3 is 0
}
13.

Explain the difference between Array, ArrayList, and List<T>.

beginner

Array:

  • Fixed size
  • Type-safe
  • Best performance
  • Zero-based indexing
    ArrayList:
  • Dynamic size
  • Stores objects (boxing for value types)
  • Not type-safe
  • Legacy, avoid in new code
    List:
  • Dynamic size
  • Type-safe with generics
  • No boxing for value types
  • Preferred choice for dynamic collections
// Array
int[] array = new int[5];
// ArrayList (avoid)
ArrayList arrayList = new ArrayList();
arrayList.Add(1);       // Boxing occurs
arrayList.Add("text");  // No compile-time type checking
// List<T> (preferred)
List<int> list = new List<int>();
list.Add(1);           // No boxing
// list.Add("text");   // Compile-time error
14.

What are the different types of generic collections in C#?

beginner

List-based:

  • List<T> - Dynamic array
  • LinkedList<T> - Doubly linked list
    Set-based:
  • HashSet<T> - Unique elements, fast lookup
  • SortedSet<T> - Sorted unique elements
    Dictionary-based:
  • Dictionary<K,V> - Key-value pairs, fast lookup
  • SortedDictionary<K,V> - Sorted key-value pairs
  • ConcurrentDictionary<K,V> - Thread-safe dictionary
    Queue/Stack:
  • Queue<T> - FIFO collection
  • Stack<T> - LIFO collection
15.

Explain the try-catch-finally block structure.

beginner

Upgrade to Premium to see the answer

Upgrade to Premium
16.

What is LINQ and what are its benefits?

beginner

Upgrade to Premium to see the answer

Upgrade to Premium
17.

Explain the difference between query syntax and method syntax in LINQ.

beginner

Upgrade to Premium to see the answer

Upgrade to Premium
18.

What are lambda expressions and how are they used in LINQ?

beginner

Upgrade to Premium to see the answer

Upgrade to Premium
19.

What is the difference between anonymous methods and lambda expressions?

beginner

Upgrade to Premium to see the answer

Upgrade to Premium
20.

What is the difference between synchronous and asynchronous programming?

beginner

Upgrade to Premium to see the answer

Upgrade to Premium
Showing 1 to 20 of 99 results

Premium Plan

$10.00 /monthly
  • Access all premium content - interview questions, and other learning resources

  • We regularly update our features and content, to ensure you get the most relevant and updated premium content.

  • 1000 monthly credits

  • Cancel anytime