Country or region and language

    Choose your country or region and your language.

    Suggested for you

      All countries and regions

        Choose your character

        It shows in the top bar and on your profile. Change it any time.

        .NET and C# interview questions with answers

        Explain what your code guarantees, then test the case that breaks a shortcut. These questions cover language behavior and service design, with separate practical interviews when you are ready to write code.

        Checked 15 November 2026

        CLR, values and memory

        What is the difference between C# and .NET? C# is a language. .NET supplies the runtime and libraries used by the application. A language version and a runtime version describe different things. The course uses a pinned browser compiler, so a feature in newer native C# documentation may not compile here.

        Does a struct always live on the stack? No. A value type can be part of a heap object or be boxed. Assignment copies its value; assigning a reference type copies a reference. If a struct contains a list, copying the struct still shares that list. Explain the copy and the ownership before discussing storage.

        When does boxing matter? Converting a value type to object or an implemented interface can box it. Repeating that conversion in a loop can create allocations. A generic collection can preserve the value type. Check allocation behavior in the actual hot path before changing a public interface.

        Can managed code leak memory? Yes. The GC reclaims unreachable objects; a growing cache, event subscription or static collection can keep objects reachable. A large allocation count and increasing retained memory are different observations. Use a dump or allocation trace to decide which problem you have.

        Does a collection free every object in generation zero? No. Reachability decides survival. Generations help the collector organize its work; they don’t give a disposal deadline. Forcing GC.Collect() on every request isn’t a general fix for retained objects.

        Span, disposal and ownership

        Does slicing a Span copy the data? A span is a view over contiguous memory. Slicing changes the view; it doesn’t copy the elements. A writable span over an array can change that array. Use ReadOnlySpan<T> to prevent writes through that view, and copy explicitly when independent storage is required.

        When would you use Memory instead? Memory<T> can be stored across asynchronous operations. Span<T> has lifetime restrictions and can’t remain live across an await. A span view doesn’t extend the lifetime of a rented buffer. Return pooled storage only after every user has finished.

        Does IDisposable replace the GC? Dispose releases resources according to an ownership contract. The GC manages managed memory. A file or stream can require deterministic cleanup even while its wrapper remains reachable. Releasing an owned resource twice should be safe; disposing something owned by a caller can break that caller.

        What happens when code inside using throws? Cleanup runs when control leaves the scope after acquisition, including an exception or early return. A using declaration lasts to the end of its enclosing scope. await using awaits asynchronous disposal. Construction that fails before acquisition is a separate case.

        Async and cancellation

        Does async start a new thread? It doesn’t guarantee a new thread. An async method runs synchronously until an incomplete awaited operation suspends it. Await I/O directly; putting every I/O call inside Task.Run adds scheduling without making the remote service faster.

        Why is async void risky? A caller can’t await its completion or handle its failure through a returned task. Use Task for ordinary asynchronous methods. Event handlers with a void contract are the usual exception, and still need a deliberate error policy.

        What does Task.WhenAll guarantee? The returned task finishes after every supplied task finishes. For a successful Task.WhenAll<T>, results follow input order. It doesn’t cancel siblings automatically or impose a concurrency limit. If all failures matter, inspect the completed combined task rather than assuming one caught exception describes every failure.

        Does canceling a token stop the operation? Cancellation is cooperative. Pass the token into operations and observe it where work continues. Test cancellation after the first operation starts, then verify cleanup. A method that checks only at entry misses a later cancellation.

        LINQ and generics

        When does a LINQ query run? Many sequence operators defer work until enumeration. Enumerating twice can repeat I/O or observe changed input. ToList materializes a snapshot at that point. It doesn’t freeze objects stored inside the list. Choose explicitly whether callers need fresh data or one stable report.

        Are IEnumerable and IQueryable interchangeable? They expose different execution models. A provider translates an IQueryable expression; an IEnumerable pipeline runs its delegates when enumerated. Moving a filter after materialization can transfer extra rows. A LINQ expression that works over a list may be unsupported by a database provider.

        Does a generic constraint validate an argument? A constraint specifies capabilities available for the type parameter. where T : class doesn’t validate a customer’s ID or a nonempty name. Keep business validation explicit. List<Derived> also isn’t a List<Base>: adding a different base instance would violate its element type.

        Why can a dictionary projection fail? ToDictionary requires unique keys. Decide whether duplicates mean invalid input, a group, or an aggregation. First() on an empty sequence and Average() over an empty nonnullable numeric sequence need their own contracts. Don’t hide missing data by returning a plausible zero.

        ASP.NET Core and dependency injection

        How do transient, scoped and singleton differ? Transient creates instances per resolution; scoped shares within a scope; singleton shares across the container’s lifetime. In a web request, scoped dependencies commonly share that request’s scope. A singleton that captures a scoped service can keep request state beyond its intended lifetime.

        Who disposes a resolved service? The container owns disposal for services it creates under its lifetime rules. Don’t dispose an injected shared service yourself. A background worker needing scoped work should create and dispose a scope, then resolve the scoped service inside it. Registering a service doesn’t make its mutable state thread safe.

        Why does middleware order matter? Middleware can inspect, alter or stop a request before later middleware runs. Authentication must establish identity before authorization uses it. Check the actual pipeline and endpoints. A successful isolated handler test doesn’t prove authentication, binding or middleware behavior in a hosted application.

        Is a missing record the same as invalid input? Separate malformed input, an absent record and a conflict with current state. Return a result that preserves that distinction. For example, requesting an unknown order differs from trying to cancel an order that has already shipped. Test the response contract and the stored state.

        EF Core and testing

        How would you investigate a slow report? Record its output contract, query count, rows transferred, elapsed time and allocations. Look for repeated enumeration and N+1 access before choosing a new collection or adding parallel tasks. Preserve empty groups, stable tie ordering and totals when comparing a revised query.

        When is AsNoTracking useful? A read-only query can avoid tracking entities it won’t update. A projection can also select only needed fields. Neither choice guarantees a useful index or a bounded result. Examine generated SQL and the database plan on representative data.

        Does an in-memory test prove relational behavior? It doesn’t prove SQL translation, constraints, transactions or the production query plan. Keep unit tests for business rules and use integration tests against the intended relational provider for those boundaries. A test that asserts only a mock’s call count can pass while returning the wrong report.

        What makes a useful boundary test? Change one requirement that defeats a likely wrong implementation: a valid zero, an empty input, a duplicate key, a cancellation after work starts or a failure after resource acquisition. Assert the result and relevant side effects. Test the test against a plausible defect too.

        When should an xUnit test be a Theory? Use Fact for a fixed example and Theory for a rule evaluated against several supplied data rows. Changing only the input is useful when the expected behavior is the same rule. Keep different contracts separate, and make each row capable of exposing a failure.

        Practical interview rounds

        The C# Interview Hub uses separately authored cases and follow-up questions. The skills assessment checks concepts across the course. Neither predicts an employer’s hiring decision.

        For targeted work, use the C# exercises and syntax reference, then return to the C# and .NET course. The browser runs real C# code. ASP.NET Core, EF Core, dependency injection and xUnit lessons use documented teaching stand-ins; they don’t host a production web server or relational database.

        Sources

        Your Work Gym account

        Save your progress and pick up on another device. Your browser's progress comes with you.

        or

        You can keep practicing without an account.

        Help and feedback

        Ask a question, tell us what is not working, or share an idea. We reply by email.

        What is it about?

        We use it only to reply to you.