C#
C# is the language of .NET services and Unity gameplay code: value and reference types, LINQ, async/await, records, pattern matching and spans. Interviews test the rules behind them.
on this pageshowhide
explore
- Syntax and Statements28 questions
- Entry Points & Namespaces6 questions
- Locals, Constants and Inference6 questions
- Operators, Casts and Conversions5 questions
- Numeric Precision and Overflow6 questions
- Branches and Loops5 questions
- Struct and Class Semantics28 questions
- Copying vs Sharing5 questions
- Boxing and Unboxing5 questions
- Value-Type Trade-Offs6 questions
- Equality and Hashing6 questions
- Tuples and Deconstruction6 questions
- Method Calls22 questions
- By-Reference Parameters5 questions
- Defaults, Names and Params6 questions
- Overload Resolution6 questions
- Local Function Declarations5 questions
- Classes and Hierarchies33 questions
- Fields and Properties5 questions
- Constructors and Initialization6 questions
- Overriding and Hiding5 questions
- Explicit and Default Implementations6 questions
- Visibility Levels6 questions
- Extension Members5 questions
- Immutable Data Types15 questions
- Record Classes5 questions
- Nondestructive Mutation6 questions
- Record Structs4 questions
- Pattern Syntax20 questions
- Type and Null Tests5 questions
- Switch Expression Arms5 questions
- Property and Relational Tests5 questions
- List and Slice Matching5 questions
- Null Safety Rules21 questions
- Nullable Reference Types6 questions
- Flow Analysis Attributes5 questions
- Coalescing and Conditional Access5 questions
- Nullable Value Types5 questions
- Type Parameters and Variance22 questions
- Reified Generics5 questions
- Where-Clause Constraints5 questions
- Covariance and Contravariance Rules6 questions
- Generic Math Interfaces6 questions
- Delegates and Events20 questions
- Func and Action Types5 questions
- Lambdas and Closures5 questions
- EventHandler Conventions5 questions
- Handler Leaks5 questions
- Iteration Machinery15 questions
- Yield-Based Methods5 questions
- Enumerator Contract5 questions
- Custom Sequence Operators5 questions
- LINQ24 questions
- Query and Method Syntax6 questions
- Deferred Execution6 questions
- Projection, Grouping and Joins6 questions
- IQueryable and Expression Trees6 questions
- Collection Types35 questions
- Arrays and Lists6 questions
- Dictionaries and Sets6 questions
- Read-Only Interfaces5 questions
- Queues, Stacks and Heaps6 questions
- Immutable and Frozen6 questions
- Thread-Safe Containers6 questions
- Text and Characters21 questions
- Immutability and StringBuilder6 questions
- Formatting and Literals5 questions
- Comparison and Culture5 questions
- UTF-16 and Runes5 questions
- Exceptions and Cleanup21 questions
- Throwing and Catching6 questions
- Throw or Return5 questions
- IDisposable and Using6 questions
- Async Disposal4 questions
- Async and Await42 questions
- Task-Based Methods6 questions
- Compiler State Machine4 questions
- ValueTask Rules4 questions
- Contexts and Deadlocks6 questions
- Cancellation Tokens5 questions
- Combinators and Failures6 questions
- Asynchronous Sequences6 questions
- Locks and Atomics5 questions
- Low-Allocation Code22 questions
- Span and ReadOnlySpan5 questions
- Ref Structs and Lifetimes6 questions
- Memory and Pooled Buffers5 questions
- Pointers and Stack Buffers6 questions
- Reflection and Code Generation18 questions
- Runtime Type Inspection6 questions
- Custom Attributes6 questions
- Source Generators6 questions
- Language Versions15 questions
- LangVersion and Targets5 questions
- C# 12–14 Additions4 questions
- Warnings and Analyzers6 questions
questions
422 · 18 sectionsIn C#, how do for, foreach, while and do-while differ in when they test their condition and where their loop variables live?
basics
~20 sfor and while test their condition before each pass and may run zero times; do-while tests after the body, so it runs at least once. foreach visits elements through a read-only variable, and loop variables stay inside the loop.
In C#, what do the int expressions -1000 / 3 and -1000 % 3 evaluate to, and how do you keep the fraction?
basics
~20 sWith two int operands C# divides as integers and truncates toward zero: -1000 / 3 is -333 and -1000 % 3 is -1. Convert an operand to double or decimal before dividing to keep the fraction.
In C#, when does an explicit cast like `(TemperatureReading)item` throw, and when does `item as TemperatureReading` return null instead?
basics
~20 sA cast (T)x throws InvalidCastException when the object's run-time type is incompatible with T, while x as T returns null. For a class target, null passes through both; as needs a reference or nullable target and never runs user-defined conversions.
In C#, what does the compiler generate for a Program.cs written with top-level statements, and how do args, await and return shape it?
basics
~20 sThe compiler wraps the statements in a generated static entry-point method of a partial class Program in the global namespace. args is its string[] parameter; await makes it return Task, a returned value makes it int, and both give Task<int>.
In C#, is a local declared with var dynamically typed, and where does the compiler refuse to accept var?
basics
~20 sA var local is statically typed: the compiler infers one fixed type from the initializer, exactly as if you had written it. var works only on initialized locals; fields, null initializers, multiple declarators and bare array initializers are rejected.
In C#, what happens when an int is assigned to an object variable, and what does casting it back to int do?
basics
~20 sAssigning an int to object boxes it: the runtime allocates a heap object and copies the value in. Casting back unboxes it: the runtime checks the box holds an int and copies the value out. Later changes to the local never reach the box.
In C#, what do ==, Equals and object.ReferenceEquals each compare for two strings, and why does that change when they are typed as object?
basics
~20 sIn C#, == is picked at compile time from the operands' static types: string's overload compares characters, but on two object-typed variables it tests references. Equals is virtual and still compares content; ReferenceEquals always tests identity.
In C#, `string` is a reference type, so why does a method that appends to its `string` parameter leave the caller's string unchanged?
basics
~20 sStrings are immutable: s += x builds a new string and stores it in the method's own parameter, which is a copy of the caller's reference. The caller's variable still refers to the original string, which nothing can change.
In C#, what happens when you assign a struct variable to another variable and change the copy, versus doing that with a class instance?
basics
~20 sAssigning a struct copies the whole value, so changing the new variable leaves the original untouched. Assigning a class instance copies only the reference, so both variables reach one object and an edit through either shows through both.
In C#, when should you declare a type as a struct rather than a class, and when is a class the better choice?
basics
~20 sChoose a struct for a small, immutable type that represents one logical value, stays valid when all-zero and is rarely boxed, such as a coordinate or a timestamp. Choose a class for identity, inheritance, or large or changing state.
In C#, how do you pass only a buffer size to `Export(string path, bool overwrite = false, int bufferSize = 4096)`, and which calls fail?
basics
~20 sA named argument skips the gap: Export("q3.csv", bufferSize: 8192) leaves overwrite at false. The compiler rejects an empty comma slot (CS0839), an out-of-position named argument followed by a positional one (CS8323), and unknown or repeated names.
In C#, what is a local function, and how does it differ from a private helper method declared on the class?
basics
~20 sA local function is a named method declared inside another member. Only that member can call it, it takes no access modifier, it can use the member's locals and parameters, and it can be called before its declaration.
In C#, why does a class that declares both `int Parse(string text)` and `long Parse(string text)` fail to compile, and what makes two methods valid overloads?
basics
~20 sOverloads must differ in signature: the parameter count and types, a parameter's by-reference kind, or the number of type parameters. Return type, parameter names, default values and params are not part of it, so the second Parse is error CS0111.
In C#, how do ref and out parameters differ, and what does the compiler require of the caller and of the called method?
basics
~20 sBoth pass the caller's variable by reference. A ref argument must be assigned before the call, and the method may read or change it; an out argument may be unassigned, and the method must assign it on every path that returns.
In C#, why does `Write(null)` bind to `Write(string?)` when `Write(object?)` also exists, yet fail with CS0121 once `Write(Exception?)` is declared?
basics
~20 sA null literal converts to every reference type, so the more specific parameter wins: string converts to object but not back. string and Exception do not convert to each other, so no overload is best and the call is error CS0121.
In C#, what access level does a type, a class member, an interface member and a nested type get when no access modifier is written?
basics
~10 sA top-level class, struct, interface, enum or delegate defaults to internal. A member of a class or struct, including a nested type, defaults to private. Interface members and enum members default to public.
In C#, how do the : this(...) and : base(...) constructor initializers chain constructors, and which mistakes does the compiler reject?
basics
~20 s: this(...) forwards to another constructor of the same class; : base(...) picks a base-class constructor. Without either, C# inserts base(), so a base with no parameterless constructor gives CS7036. Field initializers run once, in the constructor that calls base.
In C#, how do you declare an extension method like WordCount on string, and what does the compiler turn text.WordCount() into?
basics
~20 sDeclare a static method in a top-level, non-generic static class and put this before its first parameter. The compiler rewrites text.WordCount() into the static call StringExtensions.WordCount(text), and finds it only when that class's namespace is in scope.
In C#, what is the difference between override and new on a derived Send method, and which Send runs through a base-typed variable?
basics
~20 soverride replaces the implementation of the base virtual Send, so a Notification-typed variable still runs the derived code. new only hides the name: through a Notification variable the base Send runs, through an EmailNotification variable the hiding one.
In C#, what is the difference between implementing an interface member implicitly and explicitly, and how can callers reach each one?
basics
~20 sAn implicit implementation is a public member matching the interface member, callable through the class or the interface. An explicit one, named like IPaymentGateway.Close with no access modifier, is callable only through an interface-typed reference.
In C#, what does the compiler generate when you declare a positional record such as record Money(decimal Amount, string Currency)?
basics
~20 sA positional record gets a public init-only property per parameter, a primary constructor, a Deconstruct method, value-based Equals, GetHashCode, == and !=, a ToString listing its public members, and the copy members that with uses.
In C#, what does settings with { TenantId = "alpha" } return when settings is a record, and does settings change?
basics
~20 sA with expression returns a new record of the same run-time type, with every member copied from settings and only TenantId replaced. The original settings object is not modified; both variables now refer to different objects.
In C#, why do two Address records with the same city and equal List<string> street lines compare unequal, and how do you fix it?
basics
~10 sA record's synthesized Equals compares each field with EqualityComparer<T>.Default, and List<T> does not override Equals, so two distinct lists compare by reference. Declare Equals(Address? other) using SequenceEqual and a matching GetHashCode.
In C#, what does the compiler generate for a `record struct` that a plain `struct` with the same fields does not get?
basics
~20 sA C# record struct gets compiler-written IEquatable<T>.Equals, == and !=, a field-based GetHashCode and a member-listing ToString, plus properties and Deconstruct when positional. A plain struct only inherits ValueType's Equals, GetHashCode and type-name ToString, and has no ==.
In C#, what does `applicant is { Age: >= 18, MonthlyIncome: >= 2500m }` test, including when applicant is null?
basics
~20 sIt is a property pattern with relational subpatterns: it is true only when applicant is non-null, Age is at least 18 and MonthlyIncome is at least 2500. A null applicant fails the match without throwing.
In C#, how do you write a switch expression mapping an OrderStatus enum to a label, and how does it differ from a switch statement?
basics
~20 sA switch expression is written status switch { OrderStatus.Paid => "Paid", _ => "Other" }: comma-separated pattern => expression arms, tried in text order. Unlike a switch statement it produces a value, so each arm is an expression, never a statement block.
In C#, what does `if (payload is TextMessage text)` test and assign when payload is an object, and which values make it match?
basics
~20 sAn is test with a declaration pattern checks at run time that payload is non-null and holds a TextMessage or a subclass, then declares text holding that reference. Null and unrelated types never match, and no conversion operator runs.
In a C# switch expression over a (carrier, band) tuple, which arm wins when several match, and how do when guards affect error CS8510?
basics
~20 sThe first arm in text order whose pattern matches and whose when guard is true wins. An arm an earlier unguarded arm covers is error CS8510; a guard such as when kg > 20 keeps lower arms reachable, since it may fail.
In C#, how does `payload as TextMessage` followed by a null check differ from `payload is TextMessage text`, and where will as not compile?
basics
~20 sThe as form and the is pattern run the same run-time type test, but as yields null on failure, needs a separate null check and rejects non-nullable value types (CS0077). The is pattern tests and declares in one step.
In C#, what does `p?.Address?.City ?? "unknown"` evaluate to when `p` or its `Address` is null, and what does `?.` skip?
basics
~20 sIt evaluates to "unknown" in both cases. Each ?. tests the value on its left and, when that value is null, skips the rest of the access chain; ?? then replaces the null result with its right operand.
With nullable reference types enabled in C#, what does writing string? instead of string change at compile time and at run time?
basics
~20 sOnly the compiler's analysis changes. string? says the value may be null, so unchecked dereferences warn; string promises non-null, so a possible null flowing in warns. Both are System.String at run time, with no inserted null checks.
In C#, what is `int?`, and what do `HasValue`, `Value` and `GetValueOrDefault()` do when it holds no value?
basics
~10 sint? is shorthand for the struct Nullable<int>. When it is empty, HasValue is false, Value throws InvalidOperationException, and GetValueOrDefault() returns 0, or the fallback you pass to GetValueOrDefault(T).
With nullable reference types enabled, how do you annotate a C# cache's TryGetValue out parameter so callers get no warning after a true result?
basics
~10 sDeclare it [NotNullWhen(true)] out string? value: after a true return the value is not-null, after false maybe-null. For a generic TValue use [MaybeNullWhen(false)] out TValue value, as Dictionary<TKey,TValue>.TryGetValue does.
In C#, when do `??` and `??=` evaluate their right-hand operand, and what does `_avatars ??= new AvatarCache()` return?
basics
~20 sBoth evaluate the right operand only when the left one is null. _avatars ??= new AvatarCache() constructs and stores a cache on the first call and returns the stored instance on every later call, without constructing again.
In a C# generic Repository<TEntity, TKey>, why does `new TEntity()` fail to compile, and what do where-clause constraints unlock?
basics
~20 sAn unconstrained type parameter offers only System.Object's members, so new TEntity() fails with CS0304. A where clause adds guarantees: new() permits new T(), a base class or interface permits its members, and the compiler checks every type argument against them.
In C#, what does `default(T)` produce inside a generic method for `int`, `string`, `int?` and a struct, and why won't `return null;` compile?
basics
~20 sdefault(T) is the zero value of whatever type T is closed over: 0 for int, null for string and int?, a struct with every field zeroed. return null fails with CS0403 because T might be a non-nullable value type.
In C#, why can a List<OrderPlaced> be passed as IEnumerable<DomainEvent> but not assigned to a List<DomainEvent>?
basics
~10 sIEnumerable<T> declares T as out (covariant) and only hands values out, so OrderPlaced items read safely as DomainEvent. List<T> is a class, classes are always invariant, and its Add(T) would otherwise accept any DomainEvent.
In C#, why do `typeof(T)` and `value is List<T>` work inside a generic method, and how does `typeof(List<>)` differ from `typeof(List<int>)`?
basics
~20 sC# generics are reified: each closed type such as List<string> carries its type argument at run time, so typeof(T) and is List<T> see the real argument. typeof(List<>) is the open generic type definition; typeof(List<int>) is one closed type built from it.
In C#, why does `where T : new(), class` fail to compile, and in what order must a type parameter's constraints appear?
basics
~20 sC# fixes the order: one primary constraint first (a base class, or one of class, class?, struct, unmanaged, notnull), then interfaces and type parameters, then new() last. new(), class breaks both rules: CS0401 and CS0449.
In C#, when do Func, Action and Predicate fit a callback, and when do you still declare your own delegate type?
basics
~20 sFunc<..., TResult> wraps a method that returns a value, Action<...> one that returns void, and Predicate<T> a T-to-bool test. Declare your own delegate type when a parameter is ref, out or in, or when a named type should document intent.
How do you declare and raise a C# event that follows the EventHandler<TEventArgs> convention, and what goes in sender and e?
basics
~10 sDeclare event EventHandler<PriceChangedEventArgs>? PriceChanged, raise it from a protected virtual OnPriceChanged method with PriceChanged?.Invoke(this, e): sender is the publisher, e carries the data, and EventArgs.Empty stands in when there is none.
In C#, how does an expression lambda differ from a statement lambda, and where does the compiler get a lambda's parameter types?
basics
~20 sAn expression lambda's body is a single expression whose value is the result; a statement lambda's body is a block that must return explicitly on every path. Untyped parameters take their types from the delegate the lambda is converted to.
In C#, when a document window subscribes to a settings service's event, which of the two objects does the subscription keep alive, and why?
basics
~20 sThe publisher keeps the subscriber alive. The += operator stores a delegate in the settings service's event field, and that delegate's Target is the window or a closure that captured it, so the service reaches the window until it unsubscribes.
In C#, three discount rules are combined into one Func<decimal, decimal> with +=; what does invoking it return?
basics
~20 sEvery rule runs in the order it was added, each with the caller's original argument, and the call returns only the last rule's result. Earlier return values are discarded; to use them, iterate GetInvocationList() and invoke each target yourself.
In C#, how do you write a Where-style extension method over `IEnumerable<T>` with `yield return`, and how does it stream inside a pipeline?
basics
~20 sWrite a static method in a non-generic static class, take this IEnumerable<T> source, return IEnumerable<T> and yield return each match from a foreach. Nothing runs at the call; each element is then read, tested and passed on before the next.
In C#, what does a type need for foreach to compile over it, and what does the compiler turn the loop into?
basics
~20 sforeach needs a GetEnumerator() method whose return type has a public bool MoveNext() and a readable Current; no interface is required. The compiler lowers the loop to a while over MoveNext inside a try/finally that disposes a disposable enumerator.
In a C# method that returns IEnumerable<T>, what do yield return and yield break do, and why is a plain return rejected?
basics
~20 syield return hands the caller the next element and pauses the method until another is requested; yield break ends the sequence. Any yield makes the method an iterator, so a return statement, even a bare return;, is error CS1622.
In C#, when does the body of an iterator method actually start running, and what happens if its result is enumerated twice?
basics
~20 sCalling an iterator runs none of its body; it only returns an object. The body starts on the first MoveNext, pauses at each yield return, and a second foreach runs it again from the top, side effects included.
In C#, why isn't .NET's `Chunk(3)` a sliding window over sensor readings, and how do you write a `WindowBy` operator that yields safe windows?
basics
~20 sChunk(3) splits the source into disjoint arrays of three, with a shorter last one; a sliding window overlaps and advances by one. WindowBy keeps the last size elements in a Queue<T> and yields a fresh array per window, so consumers can keep each one.
In C# LINQ, when do First, FirstOrDefault, Single and SingleOrDefault each throw, and which one suits a lookup by unique key?
basics
~10 sFirst throws InvalidOperationException when nothing matches; FirstOrDefault returns default instead. Single also throws when a second match exists, and SingleOrDefault still throws on two matches: the OrDefault suffix forgives zero matches, never several.
In C# LINQ, how does query syntax such as from … where … select translate into method syntax, and which operators have no query keyword?
basics
~20 sQuery syntax is a compile-time rewrite: the C# compiler turns each clause into a method call (where to Where, select to Select, join to Join), so both forms run identical code. Distinct, Take, Count, ToList and most other operators have no keyword.
With LINQ to Objects, a Where query built before an order is added is then counted and looped over; what do Count() and foreach see?
basics
~20 sBoth see the added order. Where only stores the source and the predicate; Count() runs the filter over the list as it is at that moment, and foreach later runs it again from the start.
In C#, what is the difference between calling Where on an IEnumerable<T> and on an IQueryable<T>, and where does each filter run?
basics
~20 sWhere on an IEnumerable<T> binds Enumerable.Where: the lambda becomes a Func delegate that filters each item in memory. Where on an IQueryable<T> binds Queryable.Where: the lambda becomes an expression tree that the source's query provider executes, often in another process.
In C# LINQ, what does Select return when each department holds a list of employees, and how does SelectMany change that?
basics
~20 sSelect maps each department to one value, so selecting each department's staff list yields an IEnumerable<List<Employee>>, one list per department. SelectMany maps each department to a sequence and concatenates those sequences into one flat IEnumerable<Employee>.
In C#, what do `history[^1]` and `history[1..^1]` return for a `string[]` and for a `List<string>`, and is the range a copy?
basics
~20 shistory[^1] is the last element in both cases. history[1..^1] drops the first and last elements and returns a copy: a new string[] from the array, a new List<string> from the list, so editing it leaves history unchanged.
With C#'s Dictionary<TKey,TValue>, what does the indexer do for a missing key, and when do TryGetValue, TryAdd and Add fit better?
basics
~20 sReading a missing key through Dictionary<TKey,TValue>'s indexer throws KeyNotFoundException; writing through it adds or silently overwrites. Use TryGetValue when absence is normal, Add when a duplicate is a bug, and TryAdd to insert only if absent.
In C#, what may a caller do through IEnumerable<T>, ICollection<T>, IList<T>, IReadOnlyCollection<T> and IReadOnlyList<T>, and which should a parameter use?
basics
~10 sIEnumerable<T> only enumerates; IReadOnlyCollection<T> adds Count; IReadOnlyList<T> adds a get-only indexer; ICollection<T> adds Count, Add, Remove and Clear; IList<T> adds an indexer setter, Insert and RemoveAt. A parameter takes the least its method uses.
In C#, how do Queue<T> and Stack<T> differ in removal and enumeration order, and what happens when you Dequeue or Pop an empty one?
basics
~10 sQueue<T> is first-in-first-out (Enqueue, Dequeue) and Stack<T> is last-in-first-out (Push, Pop); foreach walks each in that removal order. Dequeue, Pop and Peek on an empty one throw InvalidOperationException; TryDequeue, TryPop and TryPeek return false.
In C#, an array's length is fixed, so how does `List<T>` grow on `Add`, and what do `Count`, `Capacity` and `EnsureCapacity` control?
basics
~20 sList<T> stores its items in an array: Count is how many it holds, Capacity is that array's length. An Add with no room allocates an array twice as long (four at first) and copies everything; a capacity hint avoids those copies.
In C#, why does building a 200,000-line CSV export with `csv += line` in a loop allocate so much, and how does StringBuilder fix it?
basics
~20 sA .NET string cannot change after creation, so csv += line compiles to csv = string.Concat(csv, line), allocating a new string and recopying all earlier text on every pass. StringBuilder appends into a growable buffer and copies once, in ToString().
In a C# interpolated string such as $"{amount,10:N2}", what do the 10 and the N2 do, and what if the value is wider?
basics
~20 sIn a hole {expr,width:format}, the comma number is a minimum width (positive right-aligns, negative left-aligns) and the colon text is the value's format string, here two-decimal N2. A wider value is printed in full, never truncated.
In C#, why does the string "👍" report a Length of 2, and what does string.Length actually count?
basics
~20 sA C# char is one UTF-16 code unit and string.Length counts code units. The thumbs-up emoji is U+1F44D, above U+FFFF, so UTF-16 stores it as a surrogate pair of two chars and Length reports 2.
In C#, what does the compiler emit for `id + "," + sku + "," + qty`, and when is `+` cheaper than StringBuilder?
basics
~20 sOne string.Concat call per expression: up to four operands use fixed-arity overloads, five or more go in a string array, and adjacent constants fold at compile time. Fixed parts allocate once; StringBuilder wins only when parts arrive in a loop.
In .NET, which StringComparison value should you pass when matching usernames, file extensions or protocol tokens, and which for text shown to people?
basics
~10 sUse StringComparison.Ordinal, or OrdinalIgnoreCase when case should not matter, for usernames, file extensions, paths, keys and protocol tokens. Use CurrentCulture or CurrentCultureIgnoreCase only for text people read, such as sorting a displayed list.
In C#, which built-in exception should a method throw for a null argument, an out-of-range argument, or a call made in the wrong object state?
basics
~10 sThrow ArgumentNullException for a null argument, ArgumentOutOfRangeException for a value outside the allowed range, and InvalidOperationException when the object's current state forbids the call. Never throw Exception, SystemException or NullReferenceException yourself.
In C#, what does a using statement do with the object it declares, and is Dispose still called when the block throws?
basics
~20 sA using statement calls Dispose on its resource when control leaves the block, however it leaves: normal completion, return, break or an exception. The compiler lowers it to try/finally, with a null check for reference types.
In C#, what is the difference between `throw;` and `throw ex;` inside a catch block, and which one should you use to rethrow?
basics
~20 sBoth rethrow the same exception object, but throw ex; restarts its stack trace at the rethrow line and hides where the failure really happened, while a bare throw; keeps the original trace. Use throw; to rethrow from a catch block.
In .NET, when should a throwing method such as Postcode.Parse get a TryParse companion, and what must that Try method still throw?
basics
~20 sAdd a TryX companion when callers routinely hit one expected failure, such as malformed input in an import: it returns false and leaves the out value at default instead of throwing. It still throws for any failure outside that defined case.
How should a sealed C# class that creates and keeps its own FileStream and database connection implement IDisposable?
basics
~20 sThe class implements IDisposable, and its Dispose disposes the fields it created, returns early on a second call, and makes later member calls throw ObjectDisposedException. Being sealed with only managed fields, it needs no finalizer and no Dispose(bool).
In C#, what is the difference between a CancellationTokenSource and a CancellationToken, and how does a cancel request reach an async method?
basics
~20 sA CancellationTokenSource sends the request: Cancel, CancelAfter and Dispose live on it. A CancellationToken is the read-only struct that code receives to observe it. Each async method takes the token and forwards it to every call that accepts one.
In C#, what does the lock statement compile to, and which object should a class lock on to guard its shared state?
basics
~20 sA C# lock (x) on an object becomes Monitor.Enter inside a try and Monitor.Exit in its finally, so an exception cannot leave the lock held. Lock on a private, dedicated object, never on this, a Type or a string.
In C#, does marking a method async make it run on a background thread, and how much of it runs before the caller gets its Task?
basics
~20 sNo. async lets a method use await and makes the compiler rewrite it; it starts no thread. The body runs on the caller's thread up to the first await of an unfinished operation, and a call that never suspends completes synchronously.
In a C# async method, what does await do when the awaited Task has not finished yet, and what does the caller get back?
basics
~20 sWhen the awaited Task is still incomplete, await suspends the async method, hands an unfinished Task back to the caller, and runs the rest of the method later as a continuation. No thread is blocked during the wait.
In C#, how do you give each imported file a 30-second limit while honouring the user's Cancel button, and tell the two apart?
basics
~10 sCreate a per-file CancellationTokenSource with a 30-second delay, combine it with the user's token through CancellationTokenSource.CreateLinkedTokenSource, and pass the linked token down. Afterwards, check which source has IsCancellationRequested set.
In C#, what is a Span<T>, what memory can it point at, and why does slicing one not copy anything?
basics
~20 sSpan<T> is a view over existing contiguous memory, such as an array, a string's characters, stackalloc memory or native memory. It holds only a reference and a length, so Slice returns another view of the same memory, not a copy.
In a C# async method that reads a stream into a buffer, why must the buffer be a Memory<byte> rather than a Span<byte>?
basics
~20 sSpan<byte> is a stack-only ref struct, so it cannot be kept across an await, which hoists live locals into a heap state machine. Memory<byte> is an ordinary struct that can live there; take its .Span only between awaits.
In a C# HTTP log parser, how do you read each line's status code and duration with ReadOnlySpan<char> instead of string.Split?
basics
~20 sView the line as a ReadOnlySpan<char>, split it into a stackalloc'd Span<Range> with MemoryExtensions.Split (.NET 8), and pass the slices straight to int.Parse and double.Parse, which accept spans. Nothing allocates per line unless you call ToString.
In C#, what is a ref struct such as Span<T>, and which uses of an ordinary struct does the compiler reject for it?
basics
~20 sA ref struct is a stack-only struct, which lets it safely hold a span or a ref field. It cannot be boxed, be an array element, be a field of a class or ordinary struct, or be captured by a lambda.
In C#, what does Span<byte> buffer = stackalloc byte[16]; allocate, and why does it compile without the unsafe keyword?
basics
~20 sIt reserves 16 bytes in the current method's stack frame and wraps them in a bounds-checked Span<byte>. The block is discarded when the method returns, never touches the GC, and is safe code because the span knows its length.
In C#, how do you declare a custom attribute such as [Traced("checkout")], and which argument types can its constructor and properties take?
basics
~20 sDeclare a class deriving from System.Attribute, conventionally named with the Attribute suffix. Constructor parameters become positional arguments and public read-write properties or fields become named ones; every argument must be a constant, a typeof expression or an array of those.
In C#, what do typeof(ICommand) and cmd.GetType() return when cmd is declared as ICommand but holds a DeployCommand?
basics
~10 stypeof(ICommand) is fixed at compile time from the type name and returns the Type for ICommand; cmd.GetType() runs on the object at run time and returns DeployCommand, its actual class.
In .NET, how do you read a custom [Traced] attribute at run time, and what do GetCustomAttribute<T>, IsDefined and the inherit argument do?
basics
~10 sGet the MemberInfo, then call GetCustomAttribute<TracedAttribute>() for one instance (null if absent, AmbiguousMatchException if several), GetCustomAttributes<T>() for all, or IsDefined for a presence check. inherit: true also searches base classes and overridden members.
In C#, what does a source generator do during compilation, and why must the type it extends be declared partial?
basics
~20 sA source generator is a compiler plug-in that inspects your code during the build and adds new C# files to the compilation. It can only add, so it extends a type by emitting another partial declaration of it.
In C#, how do [CallerMemberName] and the other caller-info attributes let OnPropertyChanged or a trace helper work without string literals?
basics
~10 sCaller-info attributes mark optional parameters that the compiler fills at each call site: [CallerMemberName] with the calling member's name, [CallerFilePath] and [CallerLineNumber] with its location, and [CallerArgumentExpression] with another argument's source text.
In a C# project, what does setting <TreatWarningsAsErrors>true</TreatWarningsAsErrors> change, and which diagnostics does it leave alone?
basics
~20 sTreatWarningsAsErrors makes the compiler report every warning it would print, CS compiler warnings and CA or IDE analyzer warnings alike, as an error that fails the build. It enables no rules and leaves suggestions and suppressed diagnostics alone.
In an SDK-style C# project with no LangVersion set, how does the TargetFramework decide which C# language version the compiler uses?
basics
~10 sThe .NET SDK maps the TargetFramework to a default C# version and passes it as LangVersion: net10.0 gets C# 14, net9.0 C# 13, net8.0 C# 12, while .NET Framework and netstandard2.0 get C# 7.3.
In upgrade notes for a C# service moving from .NET 8 to .NET 10, which headline features did C# 12, 13 and 14 add?
basics
~20 sC# 12 (.NET 8) added primary constructors for all classes and structs and collection expressions; C# 13 (.NET 9) params collections and System.Threading.Lock support; C# 14 (.NET 10) extension blocks, the field keyword and implicit span conversions.
In a .NET repository's .editorconfig, how do you set one CA rule's severity and a whole rule category's, and which entry wins when they conflict?
basics
~10 sUse dotnet_diagnostic.<rule id>.severity for one rule and dotnet_analyzer_diagnostic.category-<Category>.severity for a category. A rule-id entry beats a category entry, which beats the all-rules entry, and bulk entries only reach rules enabled by default.
A netstandard2.0 C# library shared by net48 and net10.0 apps needs records and required members; what fails, and how is it fixed?
basics
~10 sAt the default C# 7.3 both are rejected as unavailable syntax. Raising LangVersion exposes missing types instead: IsExternalInit (CS0518) and RequiredMemberAttribute plus CompilerFeatureRequiredAttribute (CS0656), which you declare yourself as internal polyfills.