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 version | C# 12 on .NET 8 |
|---|---|
| Questions | 16, easy to hard |
| Best for | Freshers and 1 to 4 years of experience |
What interviewers keep returning to
- Value versus reference semantics: assignment, parameters, equality.
- Null handling: nullable value types, nullable reference types and the operators ?., ?? and ??=.
- Resource cleanup: IDisposable, using and the garbage collector.
- Modern syntax: records, pattern matching, switch expressions, collection expressions.
C# Interview Questions and Answers: questions with worked answers
1 What is the difference between value types and reference types?
easyValue 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.
csharpstruct 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 What are boxing and unboxing, and why do they matter?
easyBoxing 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.
csharpint 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; // InvalidCastException3 How do == and Equals behave for strings and objects? Predict the output.
mediumstring 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.
csharpstring 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 Explain ref, out and in parameters.
mediumBy 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.
csharpstatic 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); // 55 const versus readonly versus static readonly.
easyconst 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 What is the difference between var, dynamic and object?
mediumvar 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.
csharpvar a = 5; // int, fixed object o = 5; // needs (int)o to do arithmetic dynamic d = 5; d = "now a string"; // allowed // a = "x"; // compile error7 Explain nullable value types and nullable reference types. What do ?., ?? and ??= do?
mediumint? 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.
csharpstring? 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 arithmetic8 What does an integer overflow do in C#?
mediumBy 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.
csharpint 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 Why use decimal for money instead of double? Predict the output.
easydouble 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.
csharpConsole.WriteLine(0.1 + 0.2 == 0.3); // False Console.WriteLine(0.1m + 0.2m == 0.3m); // True Console.WriteLine(0.1 + 0.2); // 0.3000000000000000410 What are records and how do they differ from classes?
mediumA 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.
csharppublic 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 What are primary constructors and collection expressions in C# 12?
mediumA 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.
csharppublic 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,512 How does IDisposable and the using statement work, and how does it relate to the garbage collector?
mediumThe 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.
csharpusing var reader = new StreamReader("data.txt"); string? line = reader.ReadLine(); // reader.Dispose() runs automatically at the end of the scope13 What is pattern matching, and what can a switch expression do?
mediumPatterns 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.
csharpstatic 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 string14 What are extension methods?
easyA 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>.
csharppublic static class StringExt { public static bool IsPalindrome(this string s) => s.SequenceEqual(s.Reverse()); } Console.WriteLine("level".IsPalindrome()); // True15 What does this print? Static versus instance initialisation order with inheritance.
hardIn 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.
csharpclass 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 ctor16 How does the garbage collector work in .NET?
mediumIt 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 What is the difference between string and StringBuilder?
easystring 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
- C# LINQ Interview Questions
- C# OOPs Interview Questions
- C++ Coding Interview Questions
- C++ Interview Questions and Answers
- C++ Memory Management Interview Questions
- C++ OOPS Interview Questions
- C++ Pointers and References Interview Questions
- C++ Smart Pointers Interview Questions
- C++ STL Interview Questions
- C++ Templates Interview Questions
- C++ Virtual Functions Interview Questions
- Core Java Interview Questions for Freshers