Top C# Interview Questions

C#Value TypesReference Types.NET
- Value Types: Store data directly (e.g., int, struct), allocated on the stack, copied by value. - Reference Types: Store a reference to data (e.g., class, string), allocated on the heap, copied by reference. - Comparison: Value types are faster for small data but immutable; reference types support complex objects but involve garbage collection. Example:
int a = 10; // Value type
string b = "Hello"; // Reference type
int c = a; // Copy value
string d = b; // Copy reference

C#Exception HandlingError Management
Exception handling in C# uses `try`, `catch`, `finally`, and `throw` to handle runtime errors gracefully. Example:
try {
    int x = 0;
    int y = 10 / x;
} catch (DivideByZeroException ex) {
    Console.WriteLine("Error: " + ex.Message);
} finally {
    Console.WriteLine("Cleanup");
}

C#Property AccessorsEncapsulation
Property accessors in C# are the `get` and `set` methods used to read and write a property's value, providing controlled access to a private field. Example:
class Person {
    private string name;
    public string Name {
        get { return name; }
        set { name = value; }
    }
}

C#Language Overview
C# is a modern, object-oriented programming language developed by Microsoft, used for building applications on the .NET framework, known for its type safety and versatility.

C#Continue StatementBreak StatementControl Flow
- break: Exits the loop immediately. - continue: Skips the current iteration and proceeds to the next. Example:
for (int i = 0; i < 5; i++) {
    if (i == 2) continue; // Skips 2
    if (i == 4) break;    // Exits at 4
    Console.WriteLine(i);
} // Outputs: 0, 1, 3

Master Concepts with Targeted MCQs

Strengthen your fundamentals with topic-wise MCQs designed to sharpen accuracy and speed.

C#ObjectOOP
An object is an instance of a class, containing data and behavior defined by the class, created at runtime. Example:
class Dog {
    public string Name { get; set; }
}

Dog dog = new Dog { Name = "Rex" }; // Object

C#SerializationData Persistence
Serialization is the process of converting an object into a stream of bytes for storage or transmission, and deserialization is the reverse. Example:
[Serializable]
class Person {
    public string Name { get; set; }
}

C#Partial ClassesCode Organization
Partial classes allow a class definition to be split across multiple files, useful for code organization and auto-generated code. Example:
partial class MyClass {
    public void Method1() { }
}

partial class MyClass {
    public void Method2() { }
}

C#GenericsType Safety
Generics allow defining classes, methods, or interfaces with a placeholder type, enabling type-safe, reusable code without casting. Example:
class GenericList {
    public void Add(T item) { }
}

GenericList list = new GenericList();

C#This KeywordStatic Methods
No, `this` cannot be used in a static method because it refers to the current instance, and static methods are not tied to instances. Example:
class MyClass {
    static void StaticMethod() {
        // Console.WriteLine(this); // Error
    }
}

Turn Any Job Description Into an Interview Strategy

Paste your JD to get company insights, required skills, expected questions, and a personalized prep plan.

C#Exception HandlingCatch Blocks
No, only the first matching `catch` block is executed for a given exception. Example:
try {
    throw new Exception();
} catch (ArgumentException) {
    // Not executed
} catch (Exception) {
    // Executed
}

C#Finally BlockException Handling
The `finally` block executes regardless of whether an exception occurs, ensuring cleanup tasks like closing resources are performed. Example:
try {
    // Code that may throw exception
} catch {
    // Handle exception
} finally {
    Console.WriteLine("Always executed");
}

C#Class TypesOOP
- Concrete: Instantiable classes. - Abstract: Cannot be instantiated, used as base classes. - Sealed: Cannot be inherited. - Static: Contains only static members. - Partial: Split across multiple files. Example:
abstract class A { }
sealed class B { }
static class C { }
partial class D { }

C#Managed CodeUnmanaged Code.NET
- Managed Code: Runs under CLR, with memory management (e.g., C#). - Unmanaged Code: Runs outside CLR, no automatic memory management (e.g., C++).

C#StringStringBuilderPerformance
- string: Immutable, each modification creates a new object. - StringBuilder: Mutable, efficient for frequent modifications. Example:
StringBuilder sb = new StringBuilder();
sb.Append("Hello");
sb.Append("World");

Experience a Real Interview

Practice with expert evaluators and receive detailed feedback to improve instantly.

C#Reference TypesData Types
Reference types store a reference to data on the heap (e.g., classes, interfaces, arrays, strings). Example:
string s = "Hello"; // Reference type
object o = new object();

C#LINQQuerying
LINQ (Language Integrated Query) is a set of extensions for querying data in C#, supporting collections, databases, XML, etc. Example:
int[] numbers = { 1, 2, 3, 4 };
var even = from n in numbers where n % 2 == 0 select n;

C#ClassStructComparison
- Class: Reference type, heap-allocated, supports inheritance. - Structure: Value type, stack-allocated, no inheritance. Example:
class MyClass { public int X; }
struct MyStruct { public int X; }

C#BoxingUnboxingPerformance
- Boxing: Converting a value type to a reference type (object). - Unboxing: Converting a reference type back to a value type. Example:
int i = 123;
object o = i; // Boxing
int j = (int)o; // Unboxing

C#StructClassComparison
Same as Q19: Class is reference type, struct is value type; classes support inheritance, structs do not. Example:
class C { public int X; }
struct S { public int X; }

Master Concepts with Targeted MCQs

Strengthen your fundamentals with topic-wise MCQs designed to sharpen accuracy and speed.

C#Abstract ClassOOP
An abstract class cannot be instantiated and may contain abstract methods (no implementation) and concrete methods, used as a base class. Example:
abstract class Shape {
    public abstract void Draw();
}

C#NamespaceCode Organization
A namespace organizes code into logical groups to avoid naming conflicts and improve readability. Example:
namespace MyApp {
    class MyClass { }
}

C#Method ParametersParameter Passing
- Value: Copy of the value. - Reference (ref): Reference to the variable. - Output (out): For returning values. - Params: Variable number of arguments. Example:
void Method(int a, ref int b, out int c, params int[] d) {
    c = 0;
}

C#Nullable TypesNull Handling
Nullable types allow value types to represent `null`, using the `?` operator or `Nullable`. Example:
int? x = null;
Nullable y = null;

C#EnumData Types
An enum is a value type defining a set of named constants, typically used for fixed values. Example:
enum Days { Monday, Tuesday, Wednesday }

Turn Any Job Description Into an Interview Strategy

Paste your JD to get company insights, required skills, expected questions, and a personalized prep plan.

C#Exception HandlingMultiple Exceptions
Yes, use a single `catch` block with a base exception type or C# 6.0+ exception filters to handle multiple exceptions. Example:
try {
    // Code
} catch (Exception ex) when (ex is ArgumentNullException || ex is InvalidOperationException) {
    // Handle
}

C#RecordAssignmentCopying
- Assignment: Copies the reference (same object). - Shallow Copy: Copies top-level fields, references remain shared. - Deep Copy: Copies all fields and nested objects. Example:
record Person(string Name);
Person p1 = new Person("Alice");
Person p2 = p1; // Assignment
Person p3 = p1 with { }; // Deep copy

C#Dynamic TypesType Safety
Dynamic type variables (`dynamic`) bypass compile-time type checking, resolved at runtime. Example:
dynamic x = 10;
x = "Hello";

C#RecordClassStruct
- Record: For immutable data with value semantics. - Class: For complex objects with reference semantics. - Struct: For small, immutable data with value semantics. Example:
record R(string Name);
class C { public string Name; }
struct S { public string Name; }

C#InterfaceAccessibility
Interface methods are implicitly `public` to ensure consistent contract implementation across classes. Example:
interface IExample {
    void Method(); // Implicitly public
}

Experience a Real Interview

Practice with expert evaluators and receive detailed feedback to improve instantly.

C#RecordImmutability
A record is a reference type with value-based equality, immutability by default, and concise syntax for data objects. Example:
record Person(string Name, int Age);

C#Anonymous FunctionDelegates
An anonymous function is a method without a name, typically defined using delegates or lambda expressions. Example:
Func square = x => x * x;

C#TaskThreadAsynchronous Programming
- Thread: Low-level, OS-managed, resource-intensive. - Task: High-level, managed by Task Parallel Library, supports async/await. Example:
Task.Run(() => Console.WriteLine("Task"));
new Thread(() => Console.WriteLine("Thread")).Start();

C#IDisposableResource Management
`IDisposable` enables deterministic resource cleanup (e.g., file handles) using the `Dispose` method, often with `using`. Example:
class Resource : IDisposable {
    public void Dispose() { }
}
using (var r = new Resource()) { }

C#Sealed ClassInheritance
A sealed class cannot be inherited, preventing further derivation. Example:
sealed class MyClass { }

Master Concepts with Targeted MCQs

Strengthen your fundamentals with topic-wise MCQs designed to sharpen accuracy and speed.

C#Lambda ExpressionsDelegates
Lambda expressions are concise anonymous functions using `=>` syntax, often used with delegates or LINQ. Example:
Func square = x => x * x;

C#OverloadingOverridingPolymorphism
- Overloading: Same method name, different parameters in the same class. - Overriding: Redefining a virtual method in a derived class. Example:
class Base {
    public virtual void Method() { }
    public void Method(int x) { }
}
class Derived : Base {
    public override void Method() { }
}

C#EncapsulationOOP
Encapsulation is implemented using private fields and public properties/methods to control access. Example:
class BankAccount {
    private decimal balance;
    public decimal Balance { get => balance; }
}

C#ReflectionMetadata
Reflection allows inspecting and manipulating types, methods, and properties at runtime. Example:
Type type = typeof(string);
Console.WriteLine(type.FullName);

C#Null Coalescing OperatorNull Handling
The `??` operator returns the left operand if not null, otherwise the right operand. Example:
string s = null;
string result = s ?? "Default";

Turn Any Job Description Into an Interview Strategy

Paste your JD to get company insights, required skills, expected questions, and a personalized prep plan.

C#Sealed KeywordInheritance
Use the `sealed` keyword to prevent overriding methods or classes. Example:
class Base {
    public virtual void Method() { }
}
class Derived : Base {
    public sealed override void Method() { }
}

C#InterfaceAbstract ClassOOP
- Interface: Only signatures, supports multiple inheritance. - Abstract Class: Can include implementation, single inheritance. Example:
interface IAnimal {
    void Speak();
}
abstract class Animal {
    public abstract void Speak();
}

C#DestructorResource Management
A destructor (`~ClassName`) cleans up resources before garbage collection. Use rarely, prefer `IDisposable` for deterministic cleanup. Example:
class Resource {
    ~Resource() { }
}

C#ConstantReadonlyImmutability
- const: Compile-time constant, cannot change. - readonly: Runtime constant, set in constructor. Example:
class MyClass {
    const int C = 10;
    readonly int R;
    public MyClass() { R = 20; }
}

C#Anonymous TypesData Types
Anonymous types are immutable, compiler-generated types for temporary data, created using `new { }`. Example:
var anon = new { Name = "Alice", Age = 30 };

Experience a Real Interview

Practice with expert evaluators and receive detailed feedback to improve instantly.

C#CompilationBuild Process
C# code is compiled into Intermediate Language (IL) by the C# compiler, then JIT-compiled to machine code by the CLR at runtime.

C#ThrowException Handling
- throw: Preserves the original stack trace. - throw ex: Resets the stack trace to the current point. Example:
try {
    throw new Exception("Error");
} catch (Exception ex) {
    throw; // Preserves stack trace
}

C#Dynamic TypesObject Types
- object: Type-safe, requires casting. - dynamic: Type checked at runtime, no casting needed. Example:
object o = "Hello";
string s = (string)o;
dynamic d = "Hello";
s = d;

C#Equality OperatorEquals Method
- ==: Compares references for reference types, values for value types. - Equals(): Compares content, can be overridden. Example:
string s1 = "Hello";
string s2 = "Hello";
Console.WriteLine(s1 == s2); // True
Console.WriteLine(s1.Equals(s2)); // True

C#Virtual MethodInheritance
A virtual method can be overridden in a derived class, enabling polymorphism. Example:
class Base {
    public virtual void Method() { }
}
class Derived : Base {
    public override void Method() { }
}

Master Concepts with Targeted MCQs

Strengthen your fundamentals with topic-wise MCQs designed to sharpen accuracy and speed.

C#Using StatementResource Management
- Namespace Import: Access types without full qualification. - Resource Management: Ensures `IDisposable` objects are disposed. Example:
using System;
using (var stream = new FileStream("file.txt", FileMode.Open)) { }

C#Virtual MethodAbstract Method
- Virtual: Has default implementation, optional override. - Abstract: No implementation, must be overridden. Example:
abstract class Base {
    public virtual void V() { }
    public abstract void A();
}
class Derived : Base {
    public override void A() { }
}

C#Extension MethodsCode Reusability
Extension methods add functionality to existing types using static methods in a static class. Example:
static class StringExtensions {
    public static string Reverse(this string s) => new string(s.Reverse().ToArray());
}
string s = "Hello".Reverse();

C#Ref KeywordOut KeywordParameters
- ref: Parameter must be initialized before passing, can be read/write. - out: Must be assigned in method, cannot be read before assignment. Example:
void Method(ref int a, out int b) {
    a = a + 1;
    b = 10;
}

C#Pointer TypesUnsafe Code
Pointer types in C# (`*`) allow direct memory access in `unsafe` contexts, used for performance-critical code. Example:
unsafe {
    int x = 10;
    int* p = &x;
}

Turn Any Job Description Into an Interview Strategy

Paste your JD to get company insights, required skills, expected questions, and a personalized prep plan.

C#Internal ModifierAccess Control
An `internal` member is accessible only within the same assembly. Example:
internal class MyClass {
    internal int X;
}

C#Variable ArgumentsMethod Parameters
Yes, use the `params` keyword to accept a variable number of arguments. Example:
void Sum(params int[] numbers) {
    int total = numbers.Sum();
}
Sum(1, 2, 3);

C#IndexerProperties
Indexers allow objects to be indexed like arrays using `this` keyword. Example:
class MyCollection {
    private int[] data = new int[10];
    public int this[int i] {
        get => data[i];
        set => data[i] = value;
    }
}

C#DisposeFinalizeResource Management
- Dispose: Deterministic cleanup via `IDisposable`. - Finalize: Non-deterministic cleanup via destructor, called by GC. Example:
class Resource : IDisposable {
    public void Dispose() { }
    ~Resource() { }
}

C#SelectWhereLINQ
- Where: Filters elements based on a condition. - Select: Projects elements into a new form. Example:
var numbers = new[] { 1, 2, 3, 4 };
var even = numbers.Where(n => n % 2 == 0);
var doubled = numbers.Select(n => n * 2);

Experience a Real Interview

Practice with expert evaluators and receive detailed feedback to improve instantly.

C#FuncDelegateDelegates
- Func: Predefined delegate with return type. - delegate: Custom delegate type definition. Example:
Func f = s => s.ToUpper();
delegate string MyDelegate(string s);

C#Static ConstructorClass Initialization
A static constructor initializes static members, called automatically before first use. Example:
class MyClass {
    static MyClass() { }
}

C#Fibonacci SeriesAlgorithms
Check if a number is a Fibonacci number by generating terms or using the property that a number is Fibonacci if 5n^2 + 4 or 5n^2 - 4 is a perfect square. Example:
bool IsFibonacci(int n) {
    int a = 0, b = 1;
    while (a < n) {
        int temp = a;
        a = b;
        b = temp + b;
    }
    return a == n;
}

C#BoxingUnboxingNullable Types
Boxing a nullable type boxes the underlying value if it has one; if null, it boxes to null. Unboxing requires type matching. Example:
int? x = 10;
object o = x; // Boxed to int
int? y = (int?)o;

C#Yield KeywordIterators
The `yield` keyword creates an iterator, returning elements one at a time, useful for lazy evaluation. Example:
IEnumerable GetNumbers() {
    yield return 1;
    yield return 2;
}

Master Concepts with Targeted MCQs

Strengthen your fundamentals with topic-wise MCQs designed to sharpen accuracy and speed.

C#Operator OverloadingOOP
Yes, C# supports operator overloading using the `operator` keyword. Example:
class Vector {
    public int X;
    public static Vector operator +(Vector a, Vector b) => new Vector { X = a.X + b.X };
}

C#InterfaceAbstract ClassSealed ClassStatic ClassPartial Class
- Interface: Contract, no implementation. - Abstract Class: Partial implementation, single inheritance. - Sealed Class: No inheritance. - Static Class: Only static members. - Partial Class: Split definition. Example:
interface I { }
abstract class A { }
sealed class S { }
static class T { }
partial class P { }

C#Multiple InheritanceOOP
C# supports multiple inheritance only through interfaces, not classes. Example:
interface I1 { }
interface I2 { }
class C : I1, I2 { }

C#Lock StatementThread Safety
The `lock` statement ensures thread-safe access to shared resources. Example:
object sync = new object();
lock (sync) {
    // Critical section
}

C#ApplicationExceptionSystemExceptionExceptions
- SystemException: Base for system-related exceptions. - ApplicationException: Intended for user-defined exceptions, though not strictly enforced.

Turn Any Job Description Into an Interview Strategy

Paste your JD to get company insights, required skills, expected questions, and a personalized prep plan.

C#IEnumerableListCollections
- IEnumerable: Lazy, read-only iteration. - List: In-memory, mutable collection. Use `IEnumerable` for streaming, `List` for modification. Example:
IEnumerable numbers = new List { 1, 2, 3 };

C#Method OverloadingPolymorphism
Overload by differing in number, type, or order of parameters. Example:
class Calculator {
    public int Add(int a, int b) => a + b;
    public double Add(double a, double b) => a + b;
}

C#DelegatesEvent Handling
Use delegates for callbacks, event handling, or passing methods as parameters. Example:
delegate void MyDelegate();
MyDelegate d = () => Console.WriteLine("Hello");

C#Is OperatorAs OperatorType Checking
- is: Checks if an object is of a type. - as: Casts if compatible, returns null if not. Example:
object o = "Hello";
if (o is string) { }
string s = o as string;

C#Protected InternalAccess Modifiers
`protected internal` members are accessible within the same assembly or derived classes. Example:
class MyClass {
    protected internal int X;
}

Experience a Real Interview

Practice with expert evaluators and receive detailed feedback to improve instantly.

C#ArrayListArrayCollections
Use `ArrayList` for dynamic sizing and mixed types, arrays for fixed-size, type-safe data. Example:
ArrayList list = new ArrayList();
list.Add(1);
list.Add("Hello");

C#Equality Checking.NET
- `==`: Reference or value equality. - `Equals()`: Content equality. - `ReferenceEquals()`: Reference identity. - `IEquatable`: Custom equality. Example:
string s1 = "Hello";
string s2 = "Hello";
Console.WriteLine(s1.Equals(s2));

C#Array.CopyToArray.CloneArrays
- CopyTo(): Copies elements to an existing array. - Clone(): Creates a new array with copied elements. Example:
int[] a = { 1, 2 };
int[] b = new int[2];
a.CopyTo(b, 0);
int[] c = (int[])a.Clone();

C#FuncActionPredicateDelegates
- Func: Returns a value. - Action: No return value. - Predicate: Returns bool. Example:
Func f = x => x * 2;
Action a = x => Console.WriteLine(x);
Predicate p = x => x > 0;
💬