C#

Top 20 C# Interview Questions and Answers with Examples

Prepare for C# developer interviews with 20 commonly asked questions covering OOP, value and reference types, delegates, LINQ, async/await, garbage collection and practical C# examples.

This C# interview preparation guide focuses on understanding each concept, explaining when it matters, and supporting your answer with a practical example. Use it as a revision checklist and practise explaining the ideas in your own words.

How to use this guide: Try answering each question aloud before opening the explanation. Then adapt the example to a real application or project you have worked on.

1. What is C# and how does it run on .NET?

Answer: C# is a strongly typed, object-oriented programming language commonly used to build web, desktop, cloud and service applications. C# source code is compiled into Intermediate Language (IL). The .NET runtime loads the IL, verifies and executes it, commonly using just-in-time (JIT) compilation to produce machine code. The runtime also provides services such as memory management and exception handling.

Example

A C# project is compiled into an assembly such as MyApp.dll. Running it with the .NET host starts the runtime, which loads the assembly and executes its entry point.

2. What is the difference between value types and reference types?

Answer: A value-type variable contains its value directly. Assigning it to another variable copies that value. A reference-type variable stores a reference to an object; assigning it copies the reference, so both variables can point to the same object. Structs, enums and numeric primitives are value types; classes, arrays, delegates and strings are reference types. The stack-versus-heap explanation is only a simplification: actual storage depends on context and implementation.

Example

int a = 10;
int b = a;
b++;                 // a is still 10

var first = new List<int> { 1 };
var second = first;
second.Add(2);       // first also contains 2

3. What are boxing and unboxing in C#?

Answer: Boxing converts a value type to object or an implemented interface type. The runtime creates an object representation containing a copy of the value. Unboxing extracts the value type from that boxed object and requires the correct underlying type. Boxing can allocate memory, so generic collections such as List<int> are usually preferable to non-generic collections when storing value types.

Example

int number = 42;
object boxed = number;  // boxing
int result = (int)boxed; // unboxing

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

Answer: A class is a reference type and supports inheritance from one base class. A struct is a value type and is copied by value; it cannot inherit from another struct or class, although it can implement interfaces. Structs are best for small values with value-like behaviour and usually should be immutable. A class is generally better for larger objects with identity, shared mutable state or complex lifecycle.

Example

public readonly struct Point(int x, int y)
{
    public int X { get; } = x;
    public int Y { get; } = y;
}

public class Customer { public string Name { get; set; } = ""; }

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

Answer: An interface defines a contract that unrelated types can implement. A class can implement multiple interfaces. An abstract class can provide shared state, constructors and common implementation, while requiring derived classes to implement abstract members. Use an interface when callers need a capability or dependency contract; use an abstract base class when related types genuinely share implementation or state.

Example

public interface INotifier { void Send(string message); }
public abstract class ReportBase { public abstract void Generate(); }
public sealed class EmailNotifier : INotifier {
    public void Send(string message) => Console.WriteLine(message);
}

6. What is method overloading versus method overriding?

Answer: Overloading means multiple methods share a name but have different parameter lists; the compiler selects the best match at compile time. Overriding replaces an inherited virtual or abstract member in a derived class, enabling runtime polymorphism. Return type alone cannot distinguish overloads. An override must preserve the member signature and compatible access level.

Example

class Printer {
    public void Print(string text) { }
    public void Print(int number) { } // overload
}
class Base { public virtual string Name => "Base"; }
class Derived : Base { public override string Name => "Derived"; }

7. What is the difference between virtual, override and new?

Answer: virtual allows a derived class to replace a member. override supplies that replacement and participates in runtime dispatch through a base reference. new hides a base member rather than overriding it; the selected member then depends on the reference’s compile-time type. Hiding can be confusing, so use it only when that behaviour is intentional.

Example

Base item = new Derived();
Console.WriteLine(item.Name); // calls the override

class Base { public virtual string Name => "Base"; }
class Derived : Base { public override string Name => "Child"; }

8. What is the difference between const, readonly and static readonly?

Answer: const is a compile-time constant and is implicitly static. Its value must be known at compile time. readonly fields can be assigned at declaration or in an instance constructor. static readonly fields can be assigned at declaration or in a static constructor and are shared by the type. Prefer readonly for values calculated at runtime or values that may change between builds.

Example

public const int MaxRetries = 3;
public readonly DateTime CreatedAt = DateTime.UtcNow;
public static readonly Guid AppId = Guid.NewGuid();

9. Why is string immutable, and when should you use StringBuilder?

Answer: A .NET string cannot be modified after it is created. Operations that appear to change a string create another string. Immutability makes strings safe to share and simplifies hashing and concurrency, but repeated concatenation in a loop can create many temporary objects. Use StringBuilder when building text through many incremental changes; ordinary interpolation or concatenation is fine for a small fixed number of pieces.

Example

var builder = new StringBuilder();
foreach (var name in names)
    builder.AppendLine(name);
string output = builder.ToString();

10. What are nullable value types and nullable reference types?

Answer: A nullable value type such as int? can hold either an integer or null; it is shorthand for Nullable<int>. Nullable reference types are compiler analysis annotations that help identify possible null usage. They do not create a different runtime reference type, but they produce warnings when code may dereference null. Use null checks, null-coalescing operators and accurate annotations to make intent clear.

Example

int? age = null;
int safeAge = age ?? 0;

string? displayName = FindName();
Console.WriteLine(displayName ?? "Guest");

11. What is the difference between ref, out and in parameters?

Answer: ref passes a variable by reference and requires it to be definitely assigned before the call. out also passes by reference but the called method must assign it before returning. in passes by readonly reference, which can avoid copying larger structs while preventing reassignment of the parameter inside the method. Use these modifiers when the API benefit is clear; ordinary return values are often simpler.

Example

static bool TryGetAge(string text, out int age) =>
    int.TryParse(text, out age);

if (TryGetAge("30", out int age))
    Console.WriteLine(age);

12. What is a delegate in C#?

Answer: A delegate is a type-safe reference to a method with a specified parameter list and return type. It lets code pass behaviour as data, which is useful for callbacks, event handlers and strategies. A delegate instance can refer to a compatible static or instance method and can also be combined with other delegates. Built-in generic types such as Action and Func cover many common cases.

Example

Func<int, int, int> add = (x, y) => x + y;
Console.WriteLine(add(4, 5)); // 9

13. What is an event, and how is it different from a delegate?

Answer: An event is a publisher-controlled notification mechanism built on delegates. Subscribers can add or remove handlers, but only the declaring type can raise the event. This protects the publisher from outside code replacing or invoking its notification list directly. Use events when an object needs to announce that something happened without knowing who is listening.

Example

public event EventHandler? Saved;
protected void OnSaved() => Saved?.Invoke(this, EventArgs.Empty);

14. What is the difference between Action, Func and Predicate?

Answer: Action represents a delegate that returns no value. Func represents one that returns a value, with the last generic type parameter representing the return type. Predicate<T> represents a method that accepts a T and returns a Boolean. They make APIs concise and are commonly used in LINQ, callbacks and filtering.

Example

Action<string> log = message => Console.WriteLine(message);
Func<int, bool> isEven = n => n % 2 == 0;
Predicate<string> hasText = s => !string.IsNullOrWhiteSpace(s);

15. What is deferred execution in LINQ?

Answer: Many LINQ operators build a query that is executed only when it is enumerated, for example by a foreach, ToList or Count. This is called deferred execution. It can be useful because the query sees data at enumeration time, but repeated enumeration may repeat work or observe changed data. Materialise the result when you need a stable snapshot or want to avoid running the query more than once.

Example

var query = numbers.Where(n => n > 10); // not executed yet
var results = query.ToList();            // executes now

16. How do async and await work in C#?

Answer: async and await let a method suspend while an asynchronous operation is incomplete, without blocking the current thread during the wait. The compiler transforms the method into a state machine. Awaiting a task resumes the method when the task completes, usually on the captured context unless configured otherwise. Async does not automatically mean parallel execution; use it mainly for I/O-bound operations.

Example

public async Task<string> DownloadAsync(HttpClient client, string url)
{
    return await client.GetStringAsync(url);
}

17. What is the difference between Task and Thread?

Answer: A Thread is an operating-system execution thread that you can create and manage directly. A Task represents an asynchronous operation or unit of work; it is usually scheduled on the thread pool for CPU work or represents I/O completion without dedicating a thread while waiting. Prefer Task-based APIs for application code. Use explicit threads only when you have a specific low-level threading requirement.

Example

Task<int> work = Task.Run(() => Calculate());
int result = await work;

18. How should exceptions be handled in C#?

Answer: Catch exceptions where you can take meaningful action, such as translating an infrastructure error, adding context or recovering. Avoid broad empty catches because they hide failures. Use finally or resource-management constructs to clean up, and preserve the original stack trace when rethrowing with throw;. Do not use exceptions for routine control flow such as checking whether input is valid.

Example

try { SaveFile(path); }
catch (IOException ex) {
    logger.LogError(ex, "Could not save file {Path}", path);
    throw; // preserves the original stack trace
}

19. What is IDisposable and why use the using statement?

Answer: IDisposable provides a deterministic way to release resources such as file handles, database connections and streams. The using statement or declaration ensures Dispose is called even if an exception occurs. Garbage collection reclaims managed memory, but it does not guarantee timely release of external resources. For asynchronous cleanup, use IAsyncDisposable and await using when supported.

Example

using var stream = File.OpenRead("report.pdf");
// Read the file; Dispose runs at the end of the scope.

20. How does garbage collection work in .NET?

Answer: The .NET garbage collector automatically reclaims managed objects that are no longer reachable from application roots. It uses generations to optimise collection: short-lived objects are commonly collected in generation 0, while survivors may be promoted. GC reduces manual memory management but does not remove the need to dispose unmanaged resources or avoid retaining objects unintentionally. Large object allocations and excessive temporary objects can affect performance.

Example

var cache = new List<byte[]>();
// Keeping arrays in this list makes them reachable.
// Removing references allows them to become eligible for collection.

How to prepare for your interview

Do not memorise definitions word for word. Practise explaining the concept in your own words, describe when you would use it, and mention one trade-off or common mistake. For coding and database topics, write the example yourself and test the edge cases.

Use this guide as a revision checklist, then review the topics you find difficult in more depth. Interview discussions often move from fundamentals to project decisions, debugging and performance scenarios.

Keep learning with DotNetRevision. Explore the ebook library for structured study guides, interview preparation and practical professional-development resources.

Browse DotNetRevision ebooks →

CONTINUE LEARNING

More interview preparation guides

Explore related C#, .NET, EF Core, React, TypeScript and SQL Server topics.

Browse all interview guides →