Brainbotox · Lessons · Exams

C# Interview Questions, Intermediate: LINQ, Async and DI (30 questions)

by lazizanie · Programming · C# / .NET · English

30 intermediate C# interview questions with model answers: value and reference types, records, collections, LINQ, delegates and events, async/await, exceptions and dependency injection.

Take this exam on Brainbotox, with marking →

30 questions. The model answers are folded under each one.

Question 1

Q1. LINQ and deferred execution. What does this program print, and why? Then say how you would change one line so that both calls print the same number.

var numbers = new List<int> { 1, 2, 3 };
var query = numbers.Where(n => n > 1);
numbers.Add(4);
Console.WriteLine(query.Count());
numbers.Add(5);
Console.WriteLine(query.Count());
Model answer

It prints 3, then 4.

  • Where does not filter anything when it is called. It returns an object that describes the query. This is deferred execution.
  • The query runs each time it is enumerated, here by Count(), and it reads the list as it is at that moment.
  • First Count(): the list is 1, 2, 3, 4, so 2, 3 and 4 match: 3.
  • Second Count(): the list is 1, 2, 3, 4, 5, so four items match: 4.

Fix: take a snapshot by materialising the query once.

var query = numbers.Where(n => n > 1).ToList();

Now the filter runs immediately on 1, 2, 3 and both lines print 2.

What a strong candidate adds: enumerating a deferred query twice runs it twice, which matters when the source is a database or an expensive computation.

Revise: LINQ in C#: queries, deferred execution and IQueryable

Question 2

Q2. Async code review. A colleague sends you this code from an ASP.NET Core service. Name the problem in each method, explain what can go wrong at run time, and rewrite both methods correctly.

public async void SaveAsync(Order order)
{
    await _repository.SaveAsync(order);
}
public Order Load(int id)
{
    return _repository.LoadAsync(id).Result;
}
Model answer

Method 1: async void.

  • The caller gets nothing back, so it cannot await the save and does not know when it finished, or whether it finished.
  • An exception thrown inside cannot be caught by the caller. It is raised on the thread pool and can crash the process.
  • async void is only for event handlers.

Method 2: .Result (sync over async).

  • .Result blocks the current thread until the task ends. Under load this ties up thread pool threads and leads to thread pool starvation.
  • In an app with a synchronization context (WinForms, WPF, classic ASP.NET) it can deadlock.
  • A failure is wrapped in an AggregateException, not thrown as the original exception.

Corrected version: return Task and stay async all the way up.

public async Task SaveAsync(Order order)
{
    await _repository.SaveAsync(order);
}
public async Task<Order> LoadAsync(int id)
{
    return await _repository.LoadAsync(id);
}
What a strong candidate adds: accept a CancellationToken and pass it down, and note that the callers must become async too.

Revise: Async and await in C#: Task-based asynchronous programming

Question 3

Q3. Dependency injection lifetimes.

(a) Explain the three service lifetimes in ASP.NET Core: Transient, Scoped and Singleton.

(b) What is wrong with the registration below, and how would you fix it?

services.AddDbContext<ShopContext>();          // scoped
services.AddSingleton<PriceCache>();
public class PriceCache
{
    private readonly ShopContext _db;
    public PriceCache(ShopContext db) { _db = db; }
}
Model answer

(a) The three lifetimes

  • Transient: a new instance every time the service is requested.
  • Scoped: one instance per scope, which in ASP.NET Core means one per HTTP request.
  • Singleton: one instance for the whole life of the application, shared by all requests and threads.

(b) The problem: a captive dependency.

  • The singleton PriceCache is created once and keeps its ShopContext for ever, although the context was meant to live for one request.
  • A DbContext is not thread-safe, so concurrent requests using the cache will corrupt its state or throw.
  • Its change tracker keeps growing and its data goes stale.
  • With scope validation on (the default in Development), the container throws at start-up: cannot consume scoped service from singleton.

Fix: give the singleton a way to create a short-lived context when it needs one.

public class PriceCache
{
    private readonly IServiceScopeFactory _scopes;
    public PriceCache(IServiceScopeFactory scopes)
    {
        _scopes = scopes;
    }
    public async Task RefreshAsync()
    {
        using var scope = _scopes.CreateScope();
        var db = scope.ServiceProvider
            .GetRequiredService<ShopContext>();
        // read prices, then the scope disposes db
    }
}

Other valid answers: inject IDbContextFactory<ShopContext>, or register PriceCache as scoped if it does not need to be shared.

Revise: Pattern matching, IDisposable and dependency injection in C#

Question 4

Q4. Class or struct. What is the difference between a class and a struct when you assign one variable to another? When is a struct the right choice?

Model answer
  • A class is a reference type: assignment copies the reference, so both variables point to the same object.
  • A struct is a value type: assignment copies the whole value, so the two are independent.

Choose a struct for a small, immutable value with no identity (a point, a money amount, a date range), roughly 16 bytes or less. Use a class for everything else. Structs cannot inherit from other structs, but they can implement interfaces.

Question 5

Q5. Boxing. What is boxing? Show one line of code that boxes, and say why it matters for performance.

Model answer

Boxing is copying a value type into a new heap object so it can be treated as object or as an interface.

int n = 42;
object o = n;      // boxing: heap allocation + copy
int m = (int)o;    // unboxing: type check + copy

Each box is a heap allocation that the garbage collector must later clean up. In a hot loop (for example an ArrayList of ints, or string.Format with value types) this adds up. Generics such as List<int> avoid it.

Question 6

Q6. Records. What does the compiler generate for public record Person(string Name, int Age); and what does the with expression do?

Model answer

The compiler generates:

  • a constructor and init-only properties Name and Age;
  • value-based equality: Equals, GetHashCode, == and != compare the property values;
  • a readable ToString() and a Deconstruct method.
var a = new Person("Ada", 36);
var b = a with { Age = 37 };   // copy, a is unchanged

with creates a copy with some properties changed (non-destructive mutation). A record is still a reference type unless declared record struct.

Question 7

Q7. == and Equals. What does this print, and why?

object a = "hi";
object b = new string(new[] { 'h', 'i' });
Console.WriteLine(a == b);
Console.WriteLine(a.Equals(b));
Model answer

It prints False then True.

  • == is chosen at compile time from the static types. Both are object, so it is a reference comparison, and these are two different string objects.
  • Equals is a virtual method. At run time it calls string.Equals, which compares the characters.

If both variables were declared as string, == would use the string operator and print True.

Question 8

Q8. Equals and GetHashCode. Why must you override GetHashCode when you override Equals? What goes wrong if you do not?

Model answer

The rule: two objects that are equal must return the same hash code.

Dictionary and HashSet first use the hash code to pick a bucket, and only then call Equals. If equal objects have different hash codes, they land in different buckets: a lookup with an equal key finds nothing, and a set stores duplicates.

public override int GetHashCode()
    => HashCode.Combine(Name, Age);

The hash should be built from the same fields as Equals, and those fields should not change while the object is used as a key.

Question 9

Q9. Nullable reference types. What does string? mean when nullable reference types are enabled? Does it prevent a NullReferenceException at run time? What does the ! operator do?

Model answer
  • string means: not expected to be null. string? means: may be null.
  • The compiler does flow analysis and warns when you dereference a possible null or assign null to a non-nullable variable.
  • It is compile-time only. Nothing changes at run time, so a NullReferenceException is still possible, for example with data from JSON, reflection or code compiled without the feature.
  • value! is the null-forgiving operator: it silences the warning and does no check at all.

Question 10

Q10. ref, out and in. Explain the difference between the three parameter modifiers and give a typical use of each.

Model answer

All three pass the argument by reference instead of copying it.

  • ref: the caller must initialise it; the method may read and write it. Use: swapping two values.
  • out: the caller need not initialise it; the method must assign it before returning. Use: int.TryParse(s, out var n).
  • in: passed by reference but read-only. Use: avoiding the copy of a large struct.

Question 11

Q11. Collection interfaces. A method only needs to loop once over the items it receives. Which parameter type do you choose among List<T>, IList<T>, ICollection<T> and IEnumerable<T>, and what does each interface add?

Model answer

Choose IEnumerable<T>: accept the least you need, so callers can pass an array, a list, a set or a LINQ query.

  • IEnumerable<T>: iteration only (foreach).
  • ICollection<T>: adds Count, Add, Remove, Contains.
  • IList<T>: adds access by index and Insert.
  • List<T>: a concrete class, which ties callers to one implementation.

If you need the count or several passes, ask for IReadOnlyCollection<T> or IReadOnlyList<T>.

Question 12

Q12. IEnumerable and IQueryable. With Entity Framework, what is the difference between these two lines?

var a = db.Users.Where(u => u.Age > 30).ToList();
var b = db.Users.AsEnumerable().Where(u => u.Age > 30).ToList();
Model answer
  • Line a: db.Users is an IQueryable. The lambda is an expression tree that EF translates to SQL (WHERE Age > 30). Only matching rows leave the database.
  • Line b: AsEnumerable() switches to LINQ to Objects. The whole table is loaded and the filter runs in memory.

Same result, very different cost. The classic bug is a repository that returns IEnumerable<User>, so every later filter runs in memory.

Question 13

Q13. yield return. What does this print, in order?

static IEnumerable<int> Gen()
{
    Console.WriteLine("start");
    yield return 1;
    Console.WriteLine("end");
}
var g = Gen();
Console.WriteLine("before");
foreach (var x in g) Console.WriteLine(x);
Model answer

It prints before, start, 1, end.

  • Calling Gen() runs none of its body. It returns an iterator object.
  • The body starts at the first MoveNext(), made by foreach, so "before" comes first.
  • It runs to yield return 1 and pauses. The loop prints 1.
  • The next MoveNext() resumes after the yield, prints "end" and finishes.

Consequence: argument checks at the top of an iterator method also run late, at first enumeration.

Question 14

Q14. First, Single and their OrDefault forms. Explain what each of First, FirstOrDefault, Single and SingleOrDefault does on a sequence with zero, one, or several matching items.

Model answer
Method0 items1 itemSeveral
Firstthrowsthe itemthe first
FirstOrDefaultdefault (null, 0)the itemthe first
Singlethrowsthe itemthrows
SingleOrDefaultdefaultthe itemthrows

Use Single when more than one match would be a bug (lookup by unique key). Use First when you only want any or the first match: it can stop early, while Single must keep looking for a second one.

Question 15

Q15. Select and SelectMany. Each Order has a list Lines. What is the type of each result, and what is the difference?

var a = orders.Select(o => o.Lines);
var b = orders.SelectMany(o => o.Lines);
Model answer
  • a is IEnumerable<List<Line>>: one list per order, a sequence of sequences.
  • b is IEnumerable<Line>: all lines of all orders, flattened into one sequence.

Select maps one item to one result. SelectMany maps one item to many and concatenates them. Example: orders.SelectMany(o => o.Lines).Sum(l => l.Price) gives the total of every line.

Question 16

Q16. Any or Count. Why is items.Any() preferred to items.Count() > 0 on an IEnumerable<T>?

Model answer

Any() stops at the first item. Count() on a plain sequence walks through all of it to count, only to compare with zero.

  • On a lazy query or a generator, Count() can be very slow, or never end on an infinite sequence.
  • On a database query, Any() becomes EXISTS, which is cheaper than COUNT(*).

On a List<T> or array, the Count or Length property is O(1), so list.Count > 0 is fine there.

Question 17

Q17. Dictionary. How does Dictionary<TKey, TValue> find a value? What is the cost of a lookup, and what must be true of the key type?

Model answer
  1. It calls GetHashCode() on the key and uses the result to choose a bucket.
  2. Inside the bucket it compares candidates with Equals().

A lookup is O(1) on average, and O(n) in the worst case if many keys collide.

The key type needs a consistent Equals and GetHashCode, and the key must not change while it is in the dictionary: if its hash changes, the entry can no longer be found. Use TryGetValue to read without an exception and without a double lookup.

Question 18

Q18. List growth. How does List<T> store its items, and what happens when you Add to a full list? How can you avoid the cost when you know the final size?

Model answer

List<T> wraps an array. Count is the number of items in use, Capacity is the array length.

When the array is full, Add allocates a new array of double the capacity and copies the items across. So Add is O(1) amortised, with an occasional O(n) copy and a discarded array for the garbage collector.

var list = new List<int>(10_000); // no regrowth

Inserting or removing at the front is O(n), because the following items shift.

Question 19

Q19. Func, Action and Predicate. What is a delegate? Give the delegate type for: (a) a method taking two ints and returning a string, (b) a method taking a string and returning nothing, (c) a test on a User.

Model answer

A delegate is a type-safe reference to a method with a given signature. It lets you pass behaviour as a value.

  • (a) Func<int, int, string>: the last type argument is the return type.
  • (b) Action<string>: Action delegates return void.
  • (c) Predicate<User> or Func<User, bool>. LINQ uses the Func form.
Func<int, int, string> f = (a, b) => $"{a + b}";

Question 20

Q20. Captured variables. What does this print, and how do you make it print 012?

var actions = new List<Action>();
for (int i = 0; i < 3; i++)
    actions.Add(() => Console.Write(i));
foreach (var a in actions) a();
Model answer

It prints 333.

A lambda captures the variable, not its value. In a for loop there is one variable i for the whole loop, shared by the three lambdas. They run after the loop, when i is 3.

for (int i = 0; i < 3; i++)
{
    int copy = i;                 // new variable each turn
    actions.Add(() => Console.Write(copy));
}

A foreach loop does not have this problem: since C# 5 its variable is fresh on each iteration.

Question 21

Q21. Events. What does the event keyword add to a delegate field? Why do you write Changed?.Invoke(this, e)? How can an event cause a memory leak?

Model answer
  • event restricts outside code to += and -=. Only the declaring class can raise it or clear it.
  • With no subscribers the delegate is null. ?.Invoke avoids a NullReferenceException and reads the field once, which is thread-safe.
  • Leak: the publisher's delegate holds a reference to each subscriber. If a long-lived publisher (a static service) is subscribed to by short-lived objects that never -=, the publisher keeps them alive for ever.

Question 22

Q22. Generic constraints. Explain what each constraint requires: where T : class, where T : struct, where T : new(), where T : IComparable<T>. Why add constraints at all?

Model answer
  • class: T is a reference type.
  • struct: T is a non-nullable value type.
  • new(): T has a public parameterless constructor, so the code can write new T().
  • IComparable<T>: T implements that interface, so the code can call a.CompareTo(b).

Without a constraint, generic code can only use the members of object. A constraint tells the compiler what T can do, and moves errors from run time to compile time.

static T Max<T>(T a, T b) where T : IComparable<T>
    => a.CompareTo(b) >= 0 ? a : b;

Question 23

Q23. What await does. Does async/await create a new thread? Describe what happens to the current thread when the code reaches await httpClient.GetStringAsync(url).

Model answer

No thread is created.

  1. The HTTP request is started. The operating system will signal when the response arrives.
  2. The task is not complete, so await registers the rest of the method as a continuation and returns to the caller.
  3. The thread is free: in a web server it serves other requests, in a desktop app it keeps the UI responsive.
  4. When the response arrives, the continuation is scheduled and the method resumes, possibly on a different thread.

During the wait, no thread is blocked for this request. That is why async code scales.

Question 24

Q24. Sequential or concurrent. Each call below takes about one second. Roughly how long does each version take, and why?

// Version 1
var a = await GetAAsync();
var b = await GetBAsync();
var c = await GetCAsync();
// Version 2
var ta = GetAAsync();
var tb = GetBAsync();
var tc = GetCAsync();
await Task.WhenAll(ta, tb, tc);
Model answer
  • Version 1: about 3 seconds. Each call starts only after the previous one has finished.
  • Version 2: about 1 second. Calling an async method starts the operation immediately. All three are running before the first await, and Task.WhenAll waits for all of them.

Read the results afterwards with await ta or ta.Result (safe once complete). Use version 2 only when the calls are independent, and not on one DbContext, which does not allow concurrent operations.

Question 25

Q25. Task.Run. When should you use Task.Run? Is this a good idea in an ASP.NET Core controller: await Task.Run(() => _db.Users.ToList()); ?

Model answer

Task.Run queues work to the thread pool. Its purpose is CPU-bound work that must not block the current thread, typically keeping a desktop UI responsive during a calculation.

The controller line is a bad idea:

  • The request is already on a thread pool thread. Task.Run moves the work to another pool thread, which then blocks on the database. Nothing is gained, and one extra thread switch is paid.
  • For I/O, use the real async API: await _db.Users.ToListAsync(), which blocks no thread at all.

Question 26

Q26. Cancellation. How does cancellation work with CancellationToken? Does cancelling a token stop the running code by force?

Model answer

Cancellation is cooperative. Nothing is killed.

  • A CancellationTokenSource owns the signal: cts.Cancel() or cts.CancelAfter(...).
  • Its Token is passed down to every async call.
  • The code must observe it: pass it to APIs that accept one, or call token.ThrowIfCancellationRequested() in loops.
  • Cancellation surfaces as an OperationCanceledException.
public async Task<string> LoadAsync(CancellationToken ct)
{
    return await _http.GetStringAsync(_url, ct);
}

In ASP.NET Core, a CancellationToken action parameter is cancelled when the client disconnects.

Question 27

Q27. Rethrowing. What is the difference between throw; and throw ex; inside a catch block? What is an exception filter?

Model answer
  • throw; rethrows the current exception and keeps the original stack trace.
  • throw ex; resets the stack trace to this line, so you lose where the error really happened.

An exception filter is a condition on a catch clause:

catch (HttpRequestException ex)
    when (ex.StatusCode == HttpStatusCode.NotFound)
{
    return null;
}

If the condition is false the exception is not caught at all, and the stack is not unwound. To add context, wrap it: throw new OrderException("...", ex); so the original stays as InnerException.

Question 28

Q28. IDisposable and using. .NET has a garbage collector, so why does IDisposable exist? What does using var file = File.OpenRead(path); do?

Model answer

The garbage collector manages memory only, and runs at unpredictable times. Files, sockets, database connections and locks are scarce and must be released at a known moment. Dispose() is that moment.

using var calls file.Dispose() when the variable goes out of scope, even if an exception is thrown. It is equivalent to:

var file = File.OpenRead(path);
try { /* use it */ }
finally { file?.Dispose(); }

For async resources use await using with IAsyncDisposable.

Question 29

Q29. Pattern matching. Given record Circle(double R) and record Rect(double W, double H), write a method Area(object shape) with a switch expression. What happens if no arm matches? Does the order of the arms matter?

Model answer
static double Area(object shape) => shape switch
{
    Circle c           => Math.PI * c.R * c.R,
    Rect { W: var w, H: var h } => w * h,
    null               => throw new ArgumentNullException(nameof(shape)),
    _                  => throw new ArgumentException("Unknown shape")
};
  • Arms are tested from top to bottom, first match wins. Put specific patterns before general ones. The compiler reports an arm that can never be reached.
  • _ is the discard: it matches anything.
  • With no matching arm, a SwitchExpressionException is thrown at run time, and the compiler warns that the switch is not exhaustive.

Question 30

Q30. Strings. Why is this loop slow for a large n, and how do you fix it?

string s = "";
for (int i = 0; i < n; i++)
    s += i + ",";
Model answer

Strings are immutable. Each += allocates a new string and copies everything written so far. The total work grows with n², and n temporary strings become garbage.

var sb = new StringBuilder();
for (int i = 0; i < n; i++)
    sb.Append(i).Append(',');
string s = sb.ToString();

StringBuilder appends into a growing buffer, so the total work is proportional to n. For joining a known collection, string.Join(",", items) is simpler still. For two or three pieces, plain concatenation is fine.