Autocoder

C# Interview Questions and Answers

Last updated 2026-11-19

C# interviews begin with the type system: what is a value type, what is boxing, why does a struct copy but a class not. From there they move to language features that changed recently, such as records, nullable reference types, pattern matching and primary constructors.

The answers assume C# 12 on .NET 8. Each topic with its own page is linked at the end: C# OOPs, LINQ, async and await and collections.

Language versionC# 12 on .NET 8
Questions16, easy to hard
Best forFreshers and 1 to 4 years of experience

What interviewers keep returning to

C# Interview Questions and Answers: questions with worked answers

  1. 1

    What is the difference between value types and reference types?

    easy

    Value types (int, double, bool, enum, struct) store their data directly in the variable, so assignment copies the data. Reference types (class, interface, delegate, array, string) store a reference to an object on the managed heap, so assignment copies the reference and both variables see the same object. A value type that is a field of a class lives inside that object on the heap, and a local may be on the stack or in a register, so "value types live on the stack" is a simplification.

    csharp
    struct P { public int X; }
    class C { public int X; }
    var a = new P { X = 1 }; var b = a; b.X = 2;
    Console.WriteLine(a.X);            // 1  (copied)
    var c1 = new C { X = 1 }; var c2 = c1; c2.X = 2;
    Console.WriteLine(c1.X);           // 2  (same object)
  2. 2

    What are boxing and unboxing, and why do they matter?

    easy

    Boxing wraps a value type in a new object on the heap when it is converted to object or an interface type. Unboxing copies the value back and needs an explicit cast to exactly the original type. Each box allocates memory and creates GC pressure, which matters in loops and with non-generic collections such as ArrayList. Generic collections like List<int> avoid it.

    csharp
    int n = 5;
    object o = n;              // boxing
    n = 10;
    Console.WriteLine(o);      // 5, the box is a copy
    long l = (long)(int)o;     // must unbox to int first
    // long bad = (long)o;     // InvalidCastException
  3. 3

    How do == and Equals behave for strings and objects? Predict the output.

    medium

    string overloads == to compare content, but when both operands are typed as object the compiler uses reference equality. Equals on a string compares content regardless of the static type. Strings are immutable and literals are interned, so equal literals share a reference.

    csharp
    string s = "hi";
    string t = new string("hi".ToCharArray());
    object o = s;
    Console.WriteLine(s == t);              // True  (content)
    Console.WriteLine(o == (object)t);      // False (references differ)
    Console.WriteLine(o.Equals(t));         // True  (string.Equals)
    Console.WriteLine(ReferenceEquals(s, "hi")); // True (interned literal)
  4. 4

    Explain ref, out and in parameters.

    medium

    By default arguments are passed by value (the reference is copied for classes). ref passes the variable itself, so the callee can read and reassign it, and the caller must initialise it. out also passes by reference but the callee must assign it before returning and the caller need not initialise it, as in int.TryParse. in passes by reference as read-only, which avoids copying a large struct. ref readonly arrived in C# 12 for more precise intent.

    csharp
    static void Swap(ref int a, ref int b) { (a, b) = (b, a); }
    static bool TryHalf(int n, out int half) { half = n / 2; return n % 2 == 0; }
    int x = 1, y = 2; Swap(ref x, ref y);
    Console.WriteLine($"{x} {y}");                     // 2 1
    if (TryHalf(10, out var h)) Console.WriteLine(h);  // 5
  5. 5

    const versus readonly versus static readonly.

    easy

    const is a compile-time constant, implicitly static, limited to primitives, strings and null, and its value is baked into callers at compile time, so changing it needs recompiling dependants. readonly is assigned at declaration or in a constructor and can hold any type; each instance may have a different value. static readonly is initialised once per type at runtime, and is the right choice for values that are not compile-time constants such as a DateTime or a collection.

  6. 6

    What is the difference between var, dynamic and object?

    medium

    var is compile-time inference: the variable has a fixed static type taken from the initialiser. object is the base type and needs a cast to use members. dynamic defers member lookup to runtime, so errors appear as RuntimeBinderException rather than compiler errors; it is useful for COM interop and loosely typed JSON, and slower.

    csharp
    var a = 5;            // int, fixed
    object o = 5;         // needs (int)o to do arithmetic
    dynamic d = 5;
    d = "now a string";   // allowed
    // a = "x";           // compile error
  7. 7

    Explain nullable value types and nullable reference types. What do ?., ?? and ??= do?

    medium

    int? is Nullable<int>, a struct with HasValue and Value that allows null in a value type. Nullable reference types (enabled with <Nullable>enable</Nullable>) make the compiler warn when a non-nullable reference might hold null; they are compile-time annotations only and do not change the runtime. ?. calls a member only when the receiver is not null and yields null otherwise, ?? supplies a fallback for null, and ??= assigns only when the left side is null.

    csharp
    string? name = null;
    int len = name?.Length ?? 0;       // 0
    name ??= "guest";
    Console.WriteLine(name);           // guest
    int? x = null;
    Console.WriteLine(x + 1);          // empty line: null propagates in lifted arithmetic
  8. 8

    What does an integer overflow do in C#?

    medium

    By default arithmetic on non-constant ints is unchecked and wraps around silently, so int.MaxValue plus one becomes int.MinValue. A constant expression that overflows is a compile error. Wrap code in checked { } or use the checked operator (or the project setting CheckForOverflowUnderflow) to get an OverflowException instead.

    csharp
    int x = int.MaxValue;
    x++;
    Console.WriteLine(x);                       // -2147483648
    // int y = int.MaxValue + 1;                // compile error CS0220
    try { checked { int z = int.MaxValue; z++; } }
    catch (OverflowException) { Console.WriteLine("overflow"); }
  9. 9

    Why use decimal for money instead of double? Predict the output.

    easy

    double is binary floating point and cannot represent 0.1 exactly, so sums drift. decimal is a base-10 floating-point type with 28 to 29 significant digits, designed for financial values. It is slower and larger (16 bytes), but 0.1m + 0.2m equals 0.3m exactly.

    csharp
    Console.WriteLine(0.1 + 0.2 == 0.3);       // False
    Console.WriteLine(0.1m + 0.2m == 0.3m);    // True
    Console.WriteLine(0.1 + 0.2);              // 0.30000000000000004
  10. 10

    What are records and how do they differ from classes?

    medium

    A record is a type with compiler-generated value-based equality, ToString, a deconstructor and support for non-destructive mutation with with. record (a class) is a reference type; record struct is a value type. Positional records create init-only properties from the primary constructor. Two records are equal when their components are equal, not when they are the same object.

    csharp
    public record Person(string Name, int Age);
    var a = new Person("Asha", 30);
    var b = a with { Age = 31 };
    Console.WriteLine(a == new Person("Asha", 30));  // True
    Console.WriteLine(b);        // Person { Name = Asha, Age = 31 }
  11. 11

    What are primary constructors and collection expressions in C# 12?

    medium

    A primary constructor puts parameters in the type declaration (class Svc(ILogger log)) and makes them available throughout the body; for classes and structs they are captured, not automatically properties, unlike for records. Collection expressions use square brackets to create arrays, lists and spans and the spread operator .. to splice sequences.

    csharp
    public class Greeter(string name) {
        public string Hello() => $"Hi {name}";
    }
    int[] a = [1, 2, 3];
    List<int> b = [..a, 4, 5];
    Console.WriteLine(string.Join(",", b));   // 1,2,3,4,5
  12. 12

    How does IDisposable and the using statement work, and how does it relate to the garbage collector?

    medium

    The GC reclaims managed memory but not unmanaged resources such as file handles and sockets, and it runs at non-deterministic times. A type that owns such resources implements IDisposable and its Dispose method frees them immediately. using calls Dispose in a finally, including when an exception occurs. A using declaration (using var f = ...) disposes at the end of the enclosing scope. Finalisers are a last-resort safety net and add GC cost, so call GC.SuppressFinalize in Dispose.

    csharp
    using var reader = new StreamReader("data.txt");
    string? line = reader.ReadLine();
    // reader.Dispose() runs automatically at the end of the scope
  13. 13

    What is pattern matching, and what can a switch expression do?

    medium

    Patterns test the shape of a value: type patterns (x is string s), constant, relational (> 5), property ({ Age: > 18 }), list ([1, .., 9]) and logical combinators (and, or, not). A switch expression returns a value and the compiler warns if the cases are not exhaustive.

    csharp
    static string Classify(object o) => o switch {
        int n when n < 0 => "negative",
        int n => "int " + n,
        string { Length: 0 } => "empty string",
        string s => s.ToUpper(),
        null => "null",
        _ => "other"
    };
    Console.WriteLine(Classify(7));     // int 7
    Console.WriteLine(Classify(""));    // empty string
  14. 14

    What are extension methods?

    easy

    A static method in a static class whose first parameter has the this modifier appears as an instance method on that type. It is syntactic sugar resolved at compile time, cannot access private members, and an actual instance method always wins over an extension of the same name. LINQ is built entirely from extension methods on IEnumerable<T>.

    csharp
    public static class StringExt {
        public static bool IsPalindrome(this string s) =>
            s.SequenceEqual(s.Reverse());
    }
    Console.WriteLine("level".IsPalindrome());   // True
  15. 15

    What does this print? Static versus instance initialisation order with inheritance.

    hard

    In C#, field initialisers of the derived class run before the base constructor, unlike Java. A virtual method called from the base constructor therefore already sees the derived field value. The order is: derived field initialisers, base field initialisers, base constructor body, derived constructor body.

    csharp
    class A {
        public A() { Console.WriteLine("A ctor"); Show(); }
        public virtual void Show() => Console.WriteLine("A show");
    }
    class B : A {
        int x = Init();
        static int Init() { Console.WriteLine("B field"); return 5; }
        public B() { Console.WriteLine("B ctor"); }
        public override void Show() => Console.WriteLine("B show " + x);
    }
    new B();
    // B field, A ctor, B show 5, B ctor
  16. 16

    How does the garbage collector work in .NET?

    medium

    It is a generational, compacting, tracing collector with generations 0, 1 and 2, plus a large object heap for objects of 85,000 bytes or more that is collected together with generation 2. New objects start in generation 0 and survivors are promoted. Gen 0 and gen 1 collections are cheap; a gen 2 collection is expensive. Workstation GC suits client apps and favours responsiveness, while server GC uses a heap and a GC thread per core and favours throughput; you choose with the ServerGarbageCollector setting. Concurrent background GC reduces gen 2 pauses.

  17. 17

    What is the difference between string and StringBuilder?

    easy

    string is immutable, so each concatenation creates a new object; building a string in a loop is O(n squared). StringBuilder keeps a mutable buffer and appends in amortised constant time. For a few concatenations or interpolation, string is fine, and the compiler optimises constant concatenation. Use string.Join for joining collections.

Frequently asked questions

Which C# version do interviews expect?

Most ask about C# 8 to 12 features such as records, nullable reference types, pattern matching and top-level statements. Know what shipped in each.

Is C# only for Windows?

No. Since .NET Core, C# runs on Windows, Linux and macOS. See .NET Core questions.

What is the difference between a struct and a class?

A struct is a value type copied on assignment, usually small and immutable; a class is a reference type with identity. Structs cannot inherit from other types.

Where can I practise coding problems in C#?

Use the C# coding interview questions page, then the DSA topics in the DSA hub.

Related guides

More in Programming Language Interview Questions by Language

See all in this section