C# and .NET

.NET Core and C# interview questions and answers

Questions for .NET Core and C# interviews, from fresher basics such as the CLR, garbage collection and value types to the production problems interviewers ask experienced developers about. Each answer explains the why and shows a short example.

Mixed · 45 questions · Tap a question to see the answer.

  1. Q1. A legacy ASP.NET (.NET Framework) app hangs when a controller calls GetDataAsync().Result. Why, and how do you fix it?

    Classic ASP.NET and UI apps have a SynchronizationContext that lets only one thread run the request at a time. .Result blocks that thread while the awaited task wants to resume on the same context, so each waits for the other: a deadlock.

    Fix it by going async all the way: make the action async Task<IActionResult> and await the call. In library code that never needs the context, ConfigureAwait(false) also avoids the deadlock. ASP.NET Core has no SynchronizationContext, so this exact hang does not occur there, but blocking on tasks still wastes thread-pool threads and should be avoided.

    public async Task<IActionResult> Index()
    {
        var data = await _service.GetDataAsync();
        return View(data);
    }

    Official documentation

  2. Q2. What is the difference between IEnumerable<T> and IQueryable<T> when querying a database with EF Core?

    IQueryable<T> builds an expression tree that EF Core translates to SQL, so Where, OrderBy and Take run in the database and only matching rows come back.

    Once you switch to IEnumerable<T> (for example with AsEnumerable() or ToList()), later operators run in memory on rows already loaded. Filtering after ToList() on a large table loads the whole table first. Keep filters on the IQueryable and materialize at the end.

    // Good: WHERE and TOP run in SQL
    var recent = await db.Orders
        .Where(o => o.CreatedAt > since)
        .OrderByDescending(o => o.CreatedAt)
        .Take(50)
        .ToListAsync();

    Official documentation

  3. Q3. When would you use a record instead of a class in C#?

    Use a record for data whose identity is its values: DTOs, messages, events, value objects. Records give value-based equality, a readable ToString(), deconstruction and non-destructive mutation with with.

    Use a class for entities with identity and behaviour that change over time, such as an EF Core entity tracked by id. record struct is available when you want value semantics without a heap allocation.

    public record Money(decimal Amount, string Currency);
    
    var a = new Money(10, "USD");
    var b = a with { Amount = 20 };
    Console.WriteLine(a == new Money(10, "USD")); // True

    Official documentation

  4. Q4. Explain Singleton, Scoped and Transient lifetimes, and the bug caused by injecting a Scoped service into a Singleton.

    Singleton: one instance for the app's lifetime. Scoped: one instance per scope, which in ASP.NET Core means per HTTP request. Transient: a new instance every time it is resolved.

    If a Singleton takes a Scoped service (such as a DbContext) in its constructor, that scoped instance is captured forever and shared across requests and threads. This is a 'captive dependency'. With a DbContext it causes threading errors and stale data. ASP.NET Core's scope validation throws at startup in Development to catch it. Fix it by making the consumer Scoped or by creating a scope with IServiceScopeFactory when needed.

    public class Worker(IServiceScopeFactory scopes) : BackgroundService
    {
        protected override async Task ExecuteAsync(CancellationToken ct)
        {
            using var scope = scopes.CreateScope();
            var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
            // use db for this unit of work
        }
    }

    Official documentation

  5. Q5. Why is building a large string with += in a loop slow, and what should you use?

    Strings are immutable, so every += allocates a new string and copies everything so far. For n appends this is roughly O(n²) work and creates lots of garbage.

    Use StringBuilder for loops, string.Join for joining a collection, or string interpolation for a fixed number of parts.

    var sb = new StringBuilder();
    foreach (var line in lines)
        sb.AppendLine(line);
    var text = sb.ToString();

    Official documentation

  6. Q6. What does IDisposable do, and why should HttpClient usually not be wrapped in using per request?

    IDisposable releases unmanaged resources (sockets, file handles) deterministically; using calls Dispose at the end of the scope.

    HttpClient is the exception that proves the rule: creating and disposing one per request can exhaust sockets because connections linger in TIME_WAIT. Reuse clients through IHttpClientFactory (typed or named clients) or a long-lived instance with SocketsHttpHandler.PooledConnectionLifetime set so DNS changes are picked up.

    builder.Services.AddHttpClient<GitHubClient>(c =>
        c.BaseAddress = new Uri("https://api.github.com/"));

    Official documentation

  7. Q7. You need data from three independent APIs. How do you call them in parallel, and how are exceptions reported?

    Start all three tasks first, then await Task.WhenAll(...). Total time is roughly the slowest call instead of the sum.

    If several tasks fail, await rethrows only the first exception; the full set is in the returned task's Exception.InnerExceptions. Pass a CancellationToken so the others can stop when one fails if that is what you need.

    var userTask = api.GetUserAsync(id, ct);
    var ordersTask = api.GetOrdersAsync(id, ct);
    var prefsTask = api.GetPrefsAsync(id, ct);
    await Task.WhenAll(userTask, ordersTask, prefsTask);
    var user = userTask.Result; // already completed, safe

    Official documentation

  8. Q8. What do nullable reference types (string?) change at runtime?

    Nothing at runtime. They are a compile-time feature: with <Nullable>enable</Nullable> the compiler tracks whether a reference may be null and warns on likely null dereferences.

    string means 'should not be null' and string? means 'may be null'. The ! operator silences a warning but adds no check, so you still validate external input, for example with ArgumentNullException.ThrowIfNull.

    Official documentation

  9. Q9. What is the difference between value types and reference types, and when would you make a struct?

    Value types (int, DateTime, struct) hold their data directly and are copied on assignment. Reference types (class, string, arrays) are stored on the heap and variables hold a reference, so two variables can point at the same object.

    Make a struct for small, immutable values that are created in large numbers, such as a point or a money amount, where avoiding heap allocations helps. Prefer readonly struct. Large or mutable structs are a trap because every copy duplicates the data and changes to a copy are lost.

    Official documentation

  10. Q10. How do you let a long-running operation stop when the HTTP client disconnects in ASP.NET Core?

    Accept a CancellationToken parameter in the action. ASP.NET Core binds it to HttpContext.RequestAborted, which is cancelled when the client disconnects.

    Pass that token down to every async call (EF Core queries, HttpClient, delays) so work stops early and resources are freed.

    [HttpGet("report")]
    public async Task<IActionResult> Report(CancellationToken ct)
    {
        var rows = await db.Sales.Where(s => s.Year == 2026).ToListAsync(ct);
        return Ok(rows);
    }

    Official documentation

  11. Q11. What is Span<T> and what problem does it solve?

    Span<T> is a type-safe view over a contiguous block of memory (an array, a stack buffer or native memory) without copying it. Slicing a span is free, so parsing code can work on parts of a buffer without allocating substrings or sub-arrays.

    It is a ref struct, so it can only live on the stack: no fields in classes, no capture in lambdas, and no use across await. Use Memory<T> when you need to store it or use it in async code.

    ReadOnlySpan<char> line = "2026-10-16,42";
    int comma = line.IndexOf(',');
    int value = int.Parse(line[(comma + 1)..]); // no substring allocated

    Official documentation

  12. Q12. What is the difference between .NET LTS and STS releases, and which should a production team pick?

    Even-numbered releases (.NET 8, .NET 10) are Long Term Support with 3 years of patches. Odd-numbered releases (.NET 9, .NET 11) are Standard Term Support. Microsoft extended STS support to 24 months starting with .NET 9.

    Most production teams standardise on LTS and upgrade every two years. STS suits teams that want new features early and can upgrade on schedule. Either way, install the monthly servicing updates, because they contain security fixes.

    Official documentation

  13. Q13. What is the difference between .NET (formerly .NET Core) and .NET Framework?

    .NET Framework is the original Windows-only runtime. It gets security fixes but no new features, and its last version is 4.8.1. .NET (called .NET Core up to version 3.1, then just .NET from version 5) is the cross-platform, open-source successor that runs on Windows, Linux and macOS.

    New projects should use modern .NET: it is faster, supports containers and side-by-side installs, and gets a new major version every November. .NET Framework is still used for older apps that depend on Windows-only technologies such as Web Forms or WCF server.

    Official documentation

  14. Q14. What do the CLR, IL and the JIT compiler do when a .NET program runs?

    The C# compiler turns your code into Intermediate Language (IL) stored in a .dll. At run time the Common Language Runtime (CLR) loads that IL, and the Just-In-Time (JIT) compiler turns each method into native machine code the first time it is called.

    The CLR also provides garbage collection, type safety, exception handling and threading. Tiered compilation first produces quick, simple code and recompiles hot methods with more optimisation later. Native AOT is an alternative that compiles everything ahead of time for faster startup and smaller memory use, with some limits on reflection.

  15. Q15. How does garbage collection work in .NET, and what are generations?

    The garbage collector (GC) frees objects that nothing references any more. The managed heap is split into generations: new objects go into generation 0, objects that survive a collection move to generation 1 and then generation 2. Most objects die young, so collecting gen 0 often is cheap.

    Objects of 85,000 bytes or more go on the Large Object Heap, which is collected with gen 2. To help the GC: avoid creating many short-lived large objects, reuse buffers (for example with ArrayPool<T>), and do not call GC.Collect() in normal code.

    Official documentation

  16. Q16. What is boxing and unboxing, and why can it hurt performance?

    Boxing happens when a value type, such as an int, is converted to object or to an interface: the runtime copies the value into a new object on the heap. Unboxing copies it back out. Each box is an extra allocation that the GC later has to clean up.

    It often happens by accident with old non-generic collections like ArrayList, or with string formatting of value types. Generic collections such as List<int> avoid it because they store the values directly.

    object o = 42;        // boxing: allocates
    int n = (int)o;      // unboxing: copies the value back
    
    var list = new List<int> { 1, 2, 3 }; // no boxing
  17. Q17. What is the difference between an abstract class and an interface in C#?

    An abstract class is a base class that cannot be created on its own. It can hold fields, constructors and both finished and abstract methods, and a class can inherit from only one of them.

    An interface describes a contract that any class or struct can implement, and a type can implement many interfaces. Since C# 8 an interface can have default method implementations, but it still cannot hold instance fields. Use an interface for a capability shared by unrelated types (for example IComparable), and an abstract class when related types share real code and state.

  18. Q18. What do the access modifiers public, private, protected, internal and protected internal mean?

    public is visible everywhere. private is visible only inside the same type, and is the default for class members. protected is visible in the type and in classes that inherit from it. internal is visible anywhere in the same assembly (project).

    protected internal means the same assembly OR derived classes. private protected means derived classes that are also in the same assembly. Keep members as private as you can and widen them only when needed.

  19. Q19. What does the static keyword mean on a class, a field and a method?

    A static member belongs to the type itself, not to any object, so there is one copy shared by all callers. A static method cannot use this or instance fields. A static class cannot be created with new and can contain only static members; it is often used for helpers and extension methods.

    Be careful with static mutable fields in web apps: they are shared by every request and every thread, so they need locking or should be replaced with a registered service.

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

    ref passes a variable by reference: the method can read and change the caller's variable, and it must be assigned before the call. out is also by reference, but the method must assign it before returning, which is why it is used by methods like int.TryParse.

    in passes by reference but read-only. It can avoid copying a large struct, though for small structs passing by value is just as fast.

    if (int.TryParse("42", out var n))
        Console.WriteLine(n + 1);
    
    void Double(ref int x) => x *= 2;
    int v = 5; Double(ref v); // v is now 10
  21. Q21. What is the difference between == and Equals, and why override GetHashCode with Equals?

    For reference types, == checks by default whether two variables point to the same object, unless the type overloads the operator (as string does). Equals can be overridden to compare values. Records generate value-based equality for you.

    If you override Equals, you must override GetHashCode so that equal objects return the same hash code. Otherwise Dictionary and HashSet will fail to find items that are equal.

  22. Q22. What is the difference between const and readonly?

    const values are fixed at compile time and copied into every assembly that uses them, so they can only be simple types such as numbers and strings. readonly fields are set at run time, in the declaration or the constructor, and can hold any type.

    Because a const is copied into other assemblies, changing it needs those assemblies to be rebuilt. Use const for values that never change (such as the number of days in a week) and static readonly for configuration-like values.

  23. Q23. What are good practices for throwing and catching exceptions in .NET?

    Catch only exceptions you can handle, as close as possible to where you can do something useful, and let the rest reach a global handler that logs them. Use throw; rather than throw ex; when rethrowing, so the original stack trace is kept.

    Do not use exceptions for normal control flow: prefer TryParse style methods for expected failures. Clean up with using or finally, and add useful context when wrapping an exception by passing the original as the inner exception.

    try { await SaveAsync(order, ct); }
    catch (DbUpdateConcurrencyException ex)
    {
        logger.LogWarning(ex, "Order {Id} changed by someone else", order.Id);
        throw; // keeps the stack trace
    }
  24. Q24. What are generics, and what are generic constraints used for?

    Generics let you write a class or method once and use it with many types while staying type-safe, for example List<T> or Repository<T>. They avoid casts and boxing.

    Constraints limit which types can be used, so the code can rely on what the type supports: where T : class (reference type), where T : struct, where T : new() (has a parameterless constructor), where T : IEntity (implements an interface) or where T : notnull.

    public T Max<T>(T a, T b) where T : IComparable<T>
        => a.CompareTo(b) >= 0 ? a : b;
  25. Q25. What are extension methods and when are they useful?

    An extension method is a static method in a static class whose first parameter has the this keyword. It can be called as if it were an instance method of that type, without changing the type. LINQ methods such as Where and Select are extension methods on IEnumerable<T>.

    They are useful for small helpers on types you do not own, and for setting up services (builder.Services.AddMyFeature()). They cannot access private members, so they are not a way to change a class's behaviour.

    public static class StringExtensions
    {
        public static bool IsBlank(this string? s) => string.IsNullOrWhiteSpace(s);
    }
    
    if (name.IsBlank()) { /* ... */ }
  26. Q26. What is deferred execution in LINQ, and what bug can it cause?

    Most LINQ operators such as Where and Select do not run when you write them. They build a query that runs each time you enumerate it, for example in a foreach or when you call ToList().

    If you enumerate the same query twice, the work runs twice, and against a database that means two SQL queries. If the source changes in between, the results differ. Call ToList() or ToArray() once when you need a fixed result to reuse.

    var active = users.Where(u => u.IsActive); // nothing runs yet
    var count = active.Count();  // runs the filter
    var first = active.First();  // runs it again
    var list = active.ToList();  // run once, then reuse list
  27. Q27. Why should you avoid async void methods?

    An async void method cannot be awaited, so the caller does not know when it finishes, and exceptions thrown inside it cannot be caught by the caller. They are raised on the synchronization context and can crash the process.

    Use async Task instead. The only normal use of async void is event handlers, such as a button click in a desktop app, and even there the body should catch its own exceptions.

  28. Q28. How do you make shared data thread-safe in C#?

    Protect shared mutable state so only one thread changes it at a time. The lock statement does this for simple cases. For counters, Interlocked.Increment is lighter. For shared collections, use the concurrent collections such as ConcurrentDictionary<TKey, TValue>.

    You cannot await inside a lock. For async code, use SemaphoreSlim with WaitAsync. The best option is often to avoid shared mutable state altogether, for example by using immutable objects or by giving each request its own data.

    private readonly SemaphoreSlim _gate = new(1, 1);
    
    public async Task RefreshAsync(CancellationToken ct)
    {
        await _gate.WaitAsync(ct);
        try { await LoadAsync(ct); }
        finally { _gate.Release(); }
    }
  29. Q29. How does pattern matching with switch expressions make C# code simpler?

    Pattern matching lets you test the type and shape of a value and pull out its parts in one step. A switch expression returns a value for the first matching pattern and the compiler warns you when a case is missing.

    It replaces long chains of if/else with casts, and works with type patterns, property patterns, relational patterns such as > 100 and and/or combinations.

    decimal Shipping(Order o) => o switch
    {
        { Total: >= 1000 } => 0m,
        { Country: "IN" } => 49m,
        { IsExpress: true } => 299m,
        _ => 99m,
    };
  30. Q30. What are the SOLID principles, with a short example of one?

    SOLID is five design guidelines: Single responsibility (a class has one reason to change), Open/closed (extend behaviour without editing existing code), Liskov substitution (a derived class must work wherever its base class does), Interface segregation (small, focused interfaces) and Dependency inversion (depend on abstractions, not concrete classes).

    Example of dependency inversion: an OrderService takes an IEmailSender in its constructor instead of creating SmtpEmailSender itself. ASP.NET Core dependency injection then supplies the real sender, and tests can pass a fake one.

  31. Q31. What is a delegate, and how is an event different from a public delegate field?

    A delegate is a type-safe reference to a method: it stores which method to call (and the target object), so you can pass behaviour around like data. Func<T>, Action<T> and Predicate<T> are the built-in generic delegates.

    An event is a delegate with restricted access. Outside the declaring class, code can only subscribe (+=) or unsubscribe (-=); it cannot invoke the event or replace all subscribers with =. That protects the publisher and other subscribers.

    A common leak: a short-lived object subscribes to an event on a long-lived object and never unsubscribes, so the long-lived object keeps it alive.

    public class Order
    {
        public event EventHandler<decimal>? Paid;
    
        public void Pay(decimal amount) => Paid?.Invoke(this, amount);
    }
    
    order.Paid += (_, amount) => Console.WriteLine($"Paid {amount}");

    Official documentation

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

    All three are generic delegate types. Action<T1..T16> takes parameters and returns nothing. Func<T1..T16, TResult> takes parameters and returns a value; the last type argument is the return type. Predicate<T> takes one value and returns bool.

    LINQ uses Func, for example Where(Func<T, bool>). Predicate<T> appears in older APIs such as List<T>.Find. In new code Func<T, bool> is the usual choice.

    Action<string> log = msg => Console.WriteLine(msg);
    Func<int, int, int> add = (a, b) => a + b;
    Predicate<int> isEven = n => n % 2 == 0;

    Official documentation

  33. Q33. What does yield return do, and when is it useful?

    yield return turns a method into an iterator. The compiler builds a state machine, and each value is produced only when the caller asks for the next item, so the method runs lazily.

    It is useful for streaming large or endless sequences without building a whole list in memory, such as reading a big file line by line. Remember that the code runs again every time the sequence is enumerated, and exceptions appear during enumeration, not when the method is called.

    IEnumerable<string> ReadLines(string path)
    {
        using var reader = new StreamReader(path);
        while (reader.ReadLine() is { } line)
            yield return line;
    }

    Official documentation

  34. Q34. What is the difference between Task and ValueTask, and when should you use ValueTask?

    Task is a class, so every returned task is a heap allocation (some common results are cached). ValueTask is a struct that can wrap either a result or a Task, so a method that usually completes synchronously, for example from a cache, can return without allocating.

    Use ValueTask only on hot paths where that saving is measured. It has rules: await it only once, do not await it concurrently, and do not call .Result on it before it completes. If you need to do any of that, call .AsTask(). For most application code, Task is the right default.

    Official documentation

  35. Q35. What does ConfigureAwait(false) do, and do you need it in ASP.NET Core?

    By default, await resumes on the captured synchronization context, such as the UI thread in WPF or WinForms. ConfigureAwait(false) says the rest of the method can run on any thread-pool thread.

    ASP.NET Core has no synchronization context, so in application code there it makes no difference. It still matters in general-purpose libraries, which may be called from UI apps or old ASP.NET, where it avoids deadlocks and extra thread switches. In UI code, do not use it before touching UI controls.

    Official documentation

  36. Q36. What is the difference between a Thread and a Task?

    A Thread is an operating-system thread that you create and manage yourself; it is expensive to create and holds about 1 MB of stack.

    A Task represents an operation that will complete in the future. CPU work started with Task.Run runs on the shared thread pool, and I/O work such as an HTTP call uses no thread at all while it waits. Tasks also support results, exceptions, cancellation and await.

    Use tasks and async/await for almost everything. Create a dedicated thread only for rare long-running, blocking work, for example with TaskCreationOptions.LongRunning.

    Official documentation

  37. Q37. Why is looking up an item in a Dictionary faster than in a List?

    List<T>.Contains or Find checks items one by one, which is O(n). Dictionary<TKey,TValue> and HashSet<T> use the key's hash code to jump to a bucket, so lookups are O(1) on average.

    That only works if GetHashCode and Equals are implemented consistently and the key is not changed while it is in the dictionary. For many lookups against a large list, build a dictionary or hash set once and look up in it.

    var byId = customers.ToDictionary(c => c.Id);
    if (byId.TryGetValue(42, out var customer))
        Console.WriteLine(customer.Name);

    Official documentation

  38. Q38. Strings in .NET are immutable. What does that mean in practice?

    A string object never changes after it is created. Methods such as Replace, ToUpper or + return a new string and leave the original unchanged, so you must use the returned value.

    Immutability makes strings safe to share between threads and to use as dictionary keys. The cost is that many small modifications create many objects, which is why loops that build text should use StringBuilder, and why string.Equals(a, b, StringComparison.OrdinalIgnoreCase) is better than comparing ToLower() copies.

    Official documentation

  39. Q39. What is the difference between virtual/override and the new keyword on a method? What does sealed do?

    virtual allows a derived class to override a method, and the override runs even when the object is used through a base-class reference. That is polymorphism.

    new hides the base method instead. Which method runs then depends on the variable's declared type, not the real object, which surprises people and is rarely what you want.

    sealed on a class stops anyone deriving from it; sealed override on a method stops further overriding. Sealing classes that are not designed for inheritance is a good default and can also let the JIT optimise calls.

    class Animal { public virtual string Speak() => "..."; }
    class Dog : Animal { public override string Speak() => "Woof"; }
    
    Animal a = new Dog();
    Console.WriteLine(a.Speak()); // Woof

    Official documentation

  40. Q40. What do the init and required keywords do on properties?

    An init accessor lets a property be set only during object creation, in an object initializer or constructor, which makes immutable objects easy to create.

    required (C# 11) makes the compiler insist that callers set the property in the object initializer, so you cannot forget an important value even without a constructor. Together they give safe, immutable DTOs and options classes.

    public class CreateUser
    {
        public required string Email { get; init; }
        public string? DisplayName { get; init; }
    }
    
    var cmd = new CreateUser { Email = "[email protected]" }; // compile error without Email

    Official documentation

  41. Q41. What are primary constructors on classes (C# 12), and what should you watch out for?

    A primary constructor puts the parameters right after the class name. The parameters are in scope in the whole class body, which removes the boilerplate of private fields assigned in a constructor, and suits dependency injection.

    Watch out: the parameters are not readonly fields. They can be reassigned inside the class, and if you also copy one into a property, you may end up with two copies of the value. Assign to a private readonly field when you need that guarantee.

    public class OrderService(IOrderRepository repo, ILogger<OrderService> logger)
    {
        public Task<Order?> GetAsync(int id)
        {
            logger.LogInformation("Loading {Id}", id);
            return repo.FindAsync(id);
        }
    }

    Official documentation

  42. Q42. What are collection expressions in C#?

    Collection expressions (C# 12) use square brackets to create arrays, lists, spans and other collections with one syntax: int[] a = [1, 2, 3]; or List<string> names = [];. The spread element .. copies another collection in.

    The compiler picks an efficient way to build the target type. C# 15 adds a with(...) element at the start to pass constructor arguments, such as a capacity or a comparer.

    int[] first = [1, 2];
    int[] second = [3, 4];
    List<int> all = [..first, ..second, 5];

    Official documentation

  43. Q43. What is IAsyncEnumerable<T>, and when would you use it?

    IAsyncEnumerable<T> is a sequence whose items arrive asynchronously. You consume it with await foreach and produce it with an async method that uses yield return.

    Use it to stream results as they come in, such as rows from a database, pages from an API or messages from a queue, without waiting for the whole set or blocking threads. ASP.NET Core can stream an IAsyncEnumerable response as JSON, and EF Core queries can be consumed with AsAsyncEnumerable().

    async IAsyncEnumerable<Order> GetOrdersAsync([EnumeratorCancellation] CancellationToken ct = default)
    {
        for (int page = 1; ; page++)
        {
            var batch = await api.GetPageAsync(page, ct);
            if (batch.Count == 0) yield break;
            foreach (var o in batch) yield return o;
        }
    }

    Official documentation

  44. Q44. What are covariance and contravariance in C# generics?

    Covariance (out T) lets you use a more specific type where a more general one is expected for things that only produce values: an IEnumerable<string> can be used as an IEnumerable<object>.

    Contravariance (in T) is the opposite for things that only consume values: an Action<object> can be used where an Action<string> is needed, because anything that accepts an object accepts a string.

    It works only on interfaces and delegates, and only with reference types. List<T> is not covariant because it both reads and writes items.

    IEnumerable<string> names = new List<string> { "a" };
    IEnumerable<object> objects = names; // covariance
    
    Action<object> print = o => Console.WriteLine(o);
    Action<string> printString = print; // contravariance

    Official documentation

  45. Q45. What is the difference between var, object and dynamic?

    var is compile-time type inference: the variable still has one fixed static type chosen by the compiler, with full IntelliSense and type checking.

    object is the base type of everything. You can store anything in it, but you must cast to use the real members, and value types get boxed.

    dynamic turns off compile-time checking: member access is resolved at runtime, so typos become runtime exceptions. Use it only for interop, such as COM or truly dynamic data, and prefer var everywhere else.

    Official documentation

Original questions written to explain concepts; not taken from any certification exam. Spotted a mistake? See our corrections policy.