C# Exercises with Answers
Practise C# with 143 interactive exercises: multiple choice, fill-in-the-blank, output prediction and debugging. Every exercise gives instant feedback, a hint and the full solution.
Topic All topics Introduction Variables & Types Operators & Math Strings Input & Output if & switch Loops Methods Arrays Lists & Dictionaries Classes & Objects Properties & Constructors Inheritance & Polymorphism Interfaces Structs & Records Enums Exceptions Generics LINQ Delegates & Lambdas async & await Files & JSON Nullable & Patterns Unit Testing Minimal APIs Conversions and Culture Dates and Times Regular Expressions Unicode and Encoding Projects and NuGet Equality and Hashing Extension Methods Iterators and Yield Disposal and Ownership Generic Variance Attributes and Reflection Thread Safety DI Lifetimes Configuration and Options Structured Logging HTTP Clients Entity Framework Core Authentication and Authorization
All types Fill in the blanks Multiple choice Predict the output
Any level Easy Medium Hard
Score 0 / 143
Complete the code to print a message on its own line.
Console . ( "Good morning" ) ;
WriteLine prints the text and then a new line.
Check answer Show solution
What ends most statements in C#?
A A full stop B A colon C A new line D A semicolon
Missing semicolons cause error CS1002.
Show answer
Console . Write ( "A" ) ;
Console . Write ( "B" ) ;
Console . WriteLine ( "C" ) ;
A A, B and C on separate lines B ABC C A B C D An error
Write doesn't add a new line, so all three letters share one line.
Show answer
Which command builds and runs a C# project?
A dotnet start B csharp run C dotnet run D dotnet go
dotnet new creates a project; dotnet run builds and runs it.
Show answer
What do top-level statements in Program.cs replace?
A The boilerplate class Program with a static Main method B The project file C The using directives D Comments
The compiler generates the Main method for you.
Show answer
Complete the declaration to store a price exactly.
price = 4.50 m;
decimal stores money exactly; the m suffix marks a decimal literal.
Check answer Show solution
int x = ( int ) 8.9 ;
Console . WriteLine ( x) ;
A 9 B 8.9 C 8 D An error
Casting to int cuts off the fraction without rounding.
Show answer
What type does var n = 5.0; give n?
A int B decimal C float D double
A number with a decimal point and no suffix is a double.
Show answer
bool ok = int . TryParse ( "12a" , out int n) ;
Console . WriteLine ( $"{ok} {n}" ) ;
A True 12 B False 0 C False 12 D An error
"12a" isn't a valid int, so TryParse returns false and n is 0.
Show answer
Why does double total = 0.1 + 0.2; not equal 0.3 exactly?
A It's a C# bug B The + operator rounds C Doubles can only hold whole numbers D double stores numbers in binary, so many decimals are approximations
Use decimal when exact decimal results matter.
Show answer
Complete the code to add 10 to points.
int points = 5 ;
points 10 ;
+= adds to the existing value.
Check answer Show solution
Console . WriteLine ( 17 % 5 ) ;
A 3 B 2 C 3.4 D 5
5 goes into 17 three times with 2 left over.
Show answer
int x = 5 ;
int y = x++ + 1 ;
Console . WriteLine ( $"{x} {y}" ) ;
A 6 6 B 5 6 C 6 7 D 5 7
x++ uses the old value 5, so y is 6, and then x becomes 6.
Show answer
Why is name != null && name.Length > 0 safe when name is null?
A Length returns 0 for null B && short-circuits, so name.Length isn't evaluated when the first part is false C C# ignores null D It isn't safe
The second condition only runs if the first is true.
Show answer
What does Math.Round(3.5) return by default?
A 4 B 3 C 3.5 D An error
Banker's rounding sends halves to the even number, and 4 is even.
Show answer
Complete the code so the message includes the name.
string name = "Sam" ;
Console . WriteLine ( "Hi {name}" ) ;
The $ prefix turns on string interpolation.
Check answer Show solution
Console . WriteLine ( "banana" . IndexOf ( "n" ) ) ;
A 2 B 1 C 3 D -1
Indexes start at 0, so b is 0, a is 1 and n is 2.
Show answer
string s = "a,b,,c" ;
Console . WriteLine ( s. Split ( ',' ) . Length ) ;
A 4 B 3 C 5 D 6
The two commas together produce an empty string, giving a, b, "" and c.
Show answer
What does $"{9.5:F2}" produce?
A 9.5 B 10 C 9.500 D 9.50
F2 shows exactly two decimal places.
Show answer
Why is StringBuilder faster than += when building a long string in a loop?
A It compresses the text B It runs on another thread C Strings are immutable, so each += creates a new string, while StringBuilder appends to one buffer D It skips Unicode
StringBuilder avoids copying the text on every step.
Show answer
Complete the condition so the second message runs when the first condition is false.
if ( age >= 18 )
{
Console . WriteLine ( "Adult" ) ;
}
{
Console . WriteLine ( "Under 18" ) ;
}
else runs when the if condition is false.
Check answer Show solution
int stock = 0 ;
Console . WriteLine ( stock > 0 ? "Available" : "Sold out" ) ;
A Sold out B Available C 0 D An error
The condition is false, so the second value is chosen.
Show answer
int n = 15 ;
string r = n switch { < 10 => "low" , < 20 => "mid" , _ => "high" } ;
Console . WriteLine ( r) ;
A low B high C An error D mid
15 isn't below 10, but it is below 20.
Show answer
What does _ mean in a switch expression?
A Nothing B An error case C A discard that matches any value, like default D Null only
It's usually the last arm.
Show answer
What does x is >= 1 and <= 5 check?
A x is between 1 and 5, inclusive B x equals 1 or 5 C x is greater than 5 D It's invalid syntax
and combines two relational patterns.
Show answer
Fill in the blankseasy Loops Complete the loop so it visits every name.
string [ ] names = { "Ana" , "Ben" } ;
( string name in names)
{
Console . WriteLine ( name) ;
}
foreach visits each item of a collection.
Check answer Show solution
Predict the outputeasy Loops How many lines does this print?
for ( int i = 0 ; i < 4 ; i++ )
{
Console . WriteLine ( i) ;
}
A 4 B 3 C 5 D 0
i takes the values 0, 1, 2 and 3.
Show answer
Predict the outputmedium Loops
int sum = 0 ;
for ( int i = 1 ; i <= 10 ; i++ )
{
if ( i % 2 == 0 ) continue ;
sum += i;
}
Console . WriteLine ( sum) ;
A 55 B 30 C 25 D 10
Even numbers are skipped, so 1 + 3 + 5 + 7 + 9 = 25.
Show answer
Multiple choicemedium Loops Which loop always runs its body at least once?
A for B while C do-while D foreach
Its condition is checked after the body.
Show answer
Why does removing items from a list inside foreach fail?
A Lists can't remove items B Changing a collection while enumerating it throws an InvalidOperationException C foreach is read-only for numbers D It works fine
Use RemoveAll or loop backwards with for.
Show answer
Complete the method so it returns the doubled value.
int Twice ( int n)
{
n * 2 ;
}
return sends the value back to the caller.
Check answer Show solution
string Greet ( string name = "friend" ) => $"Hi {name}" ;
Console . WriteLine ( Greet ( ) ) ;
A Hi B Hi name C Hi friend D An error
The default value is used when no argument is given.
Show answer
What return type does a method that returns nothing have?
A null B empty C void D none
void means no value is returned.
Show answer
int Add ( int a, int b) => a + b;
double Add ( double a, double b) => a + b + 0.5 ;
Console . WriteLine ( Add ( 1 , 2 ) ) ;
A 3.5 B 3 C 12 D An error
Both arguments are ints, so the int overload is chosen.
Show answer
What must a method with an out parameter do?
A Read the parameter first B Assign a value to it before returning C Return void D Be static
The caller relies on getting a value back.
Show answer
Complete the code to print the number of items.
int [ ] nums = { 4 , 8 , 15 } ;
Console . WriteLine ( nums. ) ;
Length gives the number of items in an array.
Check answer Show solution
string [ ] colours = { "red" , "green" , "blue" } ;
Console . WriteLine ( colours[ 1 ] ) ;
A red B blue C An error D green
Indexes start at 0, so index 1 is the second item.
Show answer
Predict the outputmedium Arrays
int [ ] a = { 1 , 2 , 3 } ;
int [ ] b = a;
b[ 0 ] = 99 ;
Console . WriteLine ( a[ 0 ] ) ;
A 1 B 99 C 0 D An error
a and b refer to the same array.
Show answer
What does new bool[3] contain?
A Three nulls B Three trues C Three falses D Nothing, it's empty
New arrays hold default values, and the default bool is false.
Show answer
What does arr[1..^1] give for { 10, 20, 30, 40 }?
A { 20, 30 } B { 10, 20, 30 } C { 20, 30, 40 } D { 20 }
It starts at index 1 and stops before the last item.
Show answer
Complete the code to add an item to the end of the list.
var names = new List < string > ( ) ;
names. ( "Ada" ) ;
Add appends an item to a List<T>.
Check answer Show solution
var nums = new List < int > { 5 , 6 , 7 } ;
nums. RemoveAt ( 0 ) ;
Console . WriteLine ( nums[ 0 ] ) ;
A 5 B 7 C 6 D An error
Removing index 0 shifts the remaining items down.
Show answer
What happens when you read dict["missing"] for a key that doesn't exist?
A It returns null B It returns 0 C It adds the key D It throws a KeyNotFoundException
Use TryGetValue when the key might be missing.
Show answer
var set = new HashSet < int > { 1 , 2 , 2 , 3 , 3 , 3 } ;
Console . WriteLine ( set . Count ) ;
A 6 B 3 C 1 D An error
A HashSet keeps only unique values.
Show answer
Why is looking up a key in a Dictionary faster than searching a List?
A Dictionaries are sorted B Lists can't be searched C A dictionary uses the key's hash code to jump to the item instead of checking each one D It isn't faster
Lookups take about the same time however large the dictionary is.
Show answer
Complete the line to create a new Car object.
var car = Car ( ) ;
new creates an instance of a class.
Check answer Show solution
What is the default access level of a class member in C#?
A private B public C internal D protected
Members are private unless you say otherwise.
Show answer
class Box { public int Size ; }
var a = new Box { Size = 1 } ;
var b = a;
b. Size = 5 ;
Console . WriteLine ( a. Size ) ;
A 1 B 0 C An error D 5
a and b refer to the same object.
Show answer
What does a static field belong to?
A Each object separately B The class itself, shared by every instance C Only the first object D The namespace
It's accessed through the class name.
Show answer
Why keep fields private and change them through methods?
A It's faster B Private fields use less memory C Methods can validate changes, so objects can't be put into an invalid state D The compiler requires it
This is encapsulation.
Show answer
Complete the property so it can be read and written.
public string Title { get ; ; }
get allows reading and set allows writing.
Check answer Show solution
What is the name of a constructor?
A Init B Constructor C The same as the class D New
A constructor has the class's name and no return type.
Show answer
var r = new Rect { Width = 3 , Height = 4 } ;
Console . WriteLine ( r. Area ) ;
class Rect { public int Width { get ; init ; } public int Height { get ; init ; } public int Area => Width * Height ; }
A 7 B 12 C 0 D An error
Area is computed from the two properties.
Show answer
What does { get; private set; } allow?
A Anyone can read it, but only the class can change it B Nobody can read it C Anyone can change it D It can only be set once
The setter is private.
Show answer
What does the required modifier do?
A Makes the property static B Throws if the value is null at run time C Makes the property read-only D Makes the compiler insist that callers set the property when creating the object
Missing it is a compile error.
Show answer
Complete the declaration so Cat inherits from Animal.
class Cat Animal
{
}
A colon after the class name names its base class.
Check answer Show solution
How many base classes can a C# class inherit from?
A One B Two C Any number D None
C# supports single inheritance of classes, plus any number of interfaces.
Show answer
A obj = new B ( ) ;
Console . WriteLine ( obj. Name ( ) ) ;
class A { public virtual string Name ( ) => "A" ; }
class B : A { public override string Name ( ) => "B" ; }
A A B AB C B D An error
The object's real type, B, decides which override runs.
Show answer
What does : base(name) on a constructor do?
A Creates a new base object B Calls the base class constructor with name C Overrides the base class D Makes the class abstract
The base part of the object is set up first.
Show answer
What must a non-abstract class do when it inherits an abstract method?
A Nothing B Override it with an implementation C Mark it virtual D Make it static
Otherwise the compiler reports an error.
Show answer
Complete the declaration of the interface.
IPrintable
{
void Print ( ) ;
}
interface declares a contract of members.
Check answer Show solution
By convention, what do C# interface names start with?
A An underscore B The word Interface C A capital I D A lowercase i
For example IDisposable and IEnumerable.
Show answer
How many interfaces can a class implement?
A One B Two C Any number D None if it has a base class
Separate them with commas.
Show answer
IGreeter g = new Polite ( ) ;
Console . WriteLine ( g. Hello ( ) ) ;
interface IGreeter { string Hello ( ) ; }
class Polite : IGreeter { public string Hello ( ) => "Good day" ; }
A Hello B IGreeter C An error D Good day
The interface variable calls the implementation in Polite.
Show answer
What does using var conn = OpenConnection(); guarantee?
A conn.Dispose() is called when the scope ends, even if an exception is thrown B The connection is faster C The connection is reused D Nothing extra
It requires the type to implement IDisposable.
Show answer
Complete the line to make a copy of the record with a new price.
var sale = item { Price = 5 m } ;
with creates a copy with some properties changed.
Check answer Show solution
Which of these is a value type?
A DateTime B string C List<int> D An array
DateTime is a struct.
Show answer
var a = new P ( 1 , 2 ) ;
var b = new P ( 1 , 2 ) ;
Console . WriteLine ( a == b) ;
record P ( int X, int Y) ;
A False B An error C P { X = 1, Y = 2 } D True
Records compare by value.
Show answer
var s = new S { V = 1 } ;
var t = s;
t. V = 9 ;
Console . WriteLine ( s. V ) ;
struct S { public int V; }
A 9 B 1 C 0 D An error
t is a copy, so s keeps its own value.
Show answer
What does the compiler generate for record Point(int X, int Y);?
A Only a constructor B Only properties C Nothing until you add a body D A constructor, init properties, value equality, ToString and deconstruction
Positional records are compact data types.
Show answer
Fill in the blankseasy Enums Complete the declaration of the enum.
Direction { North , East , South , West }
enum declares a set of named constants.
Check answer Show solution
Predict the outputeasy Enums
Console . WriteLine ( ( int ) Color . Blue ) ;
enum Color { Red , Green , Blue }
A 2 B 3 C 1 D Blue
Values are numbered from 0, so Blue is 2.
Show answer
Multiple choicemedium Enums Which method converts user text to an enum without throwing?
A Enum.Parse B (MyEnum)text C Convert.ToEnum D Enum.TryParse
TryParse returns false for invalid text.
Show answer
Predict the outputmedium Enums
var p = Perm . Read | Perm . Write ;
Console . WriteLine ( p. HasFlag ( Perm . Write ) ) ;
[ Flags ] enum Perm { None = 0 , Read = 1 , Write = 2 }
A False B 3 C Read, Write D True
Write is one of the combined flags.
Show answer
Why should flags enum values be powers of two?
A Each option then uses its own bit, so combinations never clash B It's faster to type C The compiler requires it D So they sort correctly
1, 2, 4 and 8 never overlap when combined.
Show answer
Complete the block that always runs, whether or not an exception happens.
try { Work ( ) ; }
catch ( Exception ) { Console . WriteLine ( "Failed" ) ; }
{ Console . WriteLine ( "Done" ) ; }
finally runs in every case.
Check answer Show solution
try
{
Console . WriteLine ( "A" ) ;
throw new Exception ( "x" ) ;
Console . WriteLine ( "B" ) ;
}
catch { Console . WriteLine ( "C" ) ; }
A A B C B A C C A B D C
The throw skips the rest of the try block.
Show answer
Why put specific catch blocks before catch (Exception)?
A For speed B It's only a style choice C Specific catches run twice otherwise D The first matching catch wins, so a general catch first would hide the specific ones
The compiler reports an error if a catch can never be reached.
Show answer
What's the difference between throw; and throw ex; in a catch block?
A None B throw; keeps the original stack trace; throw ex; resets it C throw ex; is required D throw; creates a new exception
The original stack trace shows where the problem really happened.
Show answer
When should you catch Exception, the base type of all exceptions?
A At the top level of an app, to log errors and show a friendly message B Around every method call C Never D Only in constructors
Lower down, catch the specific types you can handle.
Show answer
Complete the method so it works for any type.
T Identity ( T value) => value;
The type parameter goes in angle brackets after the method name.
Check answer Show solution
var box = new Box < string > ( "hi" ) ;
Console . WriteLine ( box. Value . Length ) ;
class Box < T> ( T value) { public T Value { get ; } = value; }
A 2 B hi C 0 D An error
T is string, so Value has a Length.
Show answer
What does where T : new() allow inside the generic code?
A Using null B Inheriting from T C Comparing T values D Creating instances with new T()
It requires a public parameterless constructor.
Show answer
Console . WriteLine ( Default < int > ( ) + 1 ) ;
T Default < T> ( ) => default ! ;
A 1 B null C 0 D An error
default(int) is 0, and 0 + 1 is 1.
Show answer
Why is List<int> faster than List<object> holding the same numbers?
A It isn't B It uses less code C It stores ints directly, without boxing each one in an object D It's sorted
Generics avoid boxing value types.
Show answer
Fill in the blankseasy LINQ Complete the query to keep only prices above 10.
var expensive = prices. ( p => p > 10 ) ;
Where filters a sequence with a condition.
Check answer Show solution
Predict the outputeasy LINQ
var nums = new [ ] { 1 , 2 , 3 , 4 } ;
Console . WriteLine ( nums. Select ( n => n * 10 ) . Sum ( ) ) ;
A 10 B 40 C 100 D 1234
10 + 20 + 30 + 40 = 100.
Show answer
Multiple choicemedium LINQ What does FirstOrDefault return when nothing matches a list of objects?
A null B It throws C An empty object D The first item anyway
Default for a reference type is null.
Show answer
Predict the outputmedium LINQ
var words = new [ ] { "apple" , "avocado" , "banana" , "blueberry" , "cherry" } ;
var groups = words. GroupBy ( w => w[ 0 ] ) ;
Console . WriteLine ( groups. Count ( ) ) ;
A 5 B 2 C 1 D 3
The first letters are a, b and c.
Show answer
What does deferred execution mean in LINQ?
A Queries run on another thread B A query runs only when it's enumerated, for example by foreach or ToList C Results are cached forever D Queries run when the program ends
Changes to the source before enumeration are seen by the query.
Show answer
Complete the lambda so it doubles its input.
Func < int , int > twice = x x * 2 ;
=> separates a lambda's parameters from its body.
Check answer Show solution
Which built-in delegate type returns nothing?
A Func B Predicate C Action D Converter
Action is for methods that return void.
Show answer
Func < int , int , int > f = ( a, b) => a * b + 1 ;
Console . WriteLine ( f ( 3 , 4 ) ) ;
A 12 B 13 C 7 D 16
3 times 4 is 12, plus 1 is 13.
Show answer
int x = 1 ;
Func < int > get = ( ) => x;
x = 10 ;
Console . WriteLine ( get ( ) ) ;
A 10 B 1 C 0 D 11
The lambda captures the variable and reads its current value.
Show answer
Why can't outside code raise a class's event directly?
A Events are private B Events need async C The event keyword only allows += and -= from outside; only the declaring class can invoke it D It can, with Invoke
This protects the class's notifications.
Show answer
Complete the line to wait for the task's result.
int count = CountUsersAsync ( ) ;
await pauses until the task completes and gives its result.
Check answer Show solution
What should an async method that returns no value return?
A void B null C Task D Task<void>
async void is only for event handlers.
Show answer
Each call takes about 2 seconds. Roughly how long does this take?
await Task . WhenAll ( WorkAsync ( ) , WorkAsync ( ) , WorkAsync ( ) ) ;
A 6 seconds B 0 seconds C 4 seconds D 2 seconds
All three run at the same time.
Show answer
Why is Task.Delay better than Thread.Sleep in async code?
A It's more accurate B It's shorter to type C It waits without blocking the thread, which stays available for other work D Thread.Sleep doesn't exist
Thread.Sleep blocks the thread for the whole time.
Show answer
Which exception signals that an operation was cancelled through a CancellationToken?
A TimeoutException B OperationCanceledException C TaskException D AbortException
TaskCanceledException derives from it.
Show answer
Complete the line to read the whole file into a string.
string text = File . ( "notes.txt" ) ;
ReadAllText returns the full contents as one string.
Check answer Show solution
Which method adds text to the end of a file without removing what's there?
A File.WriteAllText B File.ReadAllText C File.Replace D File.AppendAllText
WriteAllText would overwrite the file.
Show answer
Why use Path.Combine instead of joining strings with a slash?
A It's faster B It uses the correct separator for the operating system C It creates the folder D It checks the file exists
Windows uses \ and macOS and Linux use /.
Show answer
var json = JsonSerializer . Serialize ( new { Name = "Ada" , Age = 36 } ) ;
Console . WriteLine ( json) ;
A {name:"Ada",age:36} B {"name":"Ada","age":36} C {"Name":"Ada","Age":36} D Name=Ada, Age=36
Default options keep the C# property names and produce compact JSON.
Show answer
Why is File.ReadLines better than File.ReadAllLines for a very large file?
A It's sorted B It skips empty lines C It reads in parallel D It reads one line at a time instead of loading the whole file into memory
It returns a lazily evaluated sequence of lines.
Show answer
Complete the declaration so the variable may hold null.
string middleName = null ;
The ? marks a nullable reference type.
Check answer Show solution
string ? s = null ;
Console . WriteLine ( s? . Length ? ? - 1 ) ;
A 0 B -1 C null D An exception
s?.Length is null, so ?? supplies -1.
Show answer
A Always sets x to 10 B Compares x with 10 C Adds 10 to x D Sets x to 10 only if x is null
It's null-coalescing assignment.
Show answer
var p = new Pt ( 2 , 5 ) ;
Console . WriteLine ( p is { X: > 0 , Y: > 4 } ) ;
record Pt ( int X, int Y) ;
A True B False C An error D Pt { X = 2, Y = 5 }
Both property conditions are met.
Show answer
Does the null-forgiving operator ! prevent a NullReferenceException?
A Yes B Only for strings C No, it only silences the compiler warning D Only in release builds
If the value is null, the program still crashes.
Show answer
Complete the attribute that marks a simple test in xUnit.
]
public void Adds ( ) => Assert . Equal ( 4 , 2 + 2 ) ;
[Fact] marks a test with no parameters.
Check answer Show solution
Which command runs every test in a solution?
A dotnet run tests B dotnet check C dotnet test D xunit run
It builds the projects and runs all tests.
Show answer
What does [Theory] with three [InlineData] rows produce?
A One test B Nine tests C A compile error D Three test cases, one per row
Each row supplies the parameters for one run.
Show answer
[ Fact ]
public void Divide_ByZero_Throws ( ) =>
Assert . Throws < DivideByZeroException > ( ( ) => { int z = 0 ; _ = 10 / z; } ) ;
A No, nothing is thrown B Yes C No, a different exception is thrown D It doesn't compile
Integer division by zero throws DivideByZeroException.
Show answer
Why make classes depend on interfaces like IClock rather than DateTime.Now?
A Tests can pass in a fake that returns any time they need, making results predictable B It's faster C DateTime.Now doesn't work in tests D Interfaces use less memory
This is dependency injection for testability.
Show answer
Complete the line to handle GET requests to /hello.
app. ( "/hello" , ( ) => "Hello!" ) ;
MapGet maps GET requests to a handler.
Check answer Show solution
Which status code means a new resource was created?
A 200 B 201 C 204 D 404
Results.Created returns 201 with the new item's location.
Show answer
Where does int page come from in app.MapGet("/search", (string q, int page) => ...)?
A The query string, as in /search?q=lamp&page=2 B The JSON body C A header D The route
Simple types not in the route bind from the query string.
Show answer
A request is sent to /products/abc. What happens with this route?
app. MapGet ( "/products/{id:int}" , ( int id) => id) ;
A It returns 0 B The route doesn't match, so the response is 404 C It returns 500 D It returns "abc"
The int constraint rejects non-numeric values.
Show answer
Which service lifetime is usually right for a database context?
A Scoped (one per request) B Singleton C Transient D Static
Each request gets its own context, which is disposed when the request ends.
Show answer
An imported value of 2.9 must be rejected because quantities are whole numbers. Which approach satisfies the rule?
A Display F0 and keep the original value. B Cast it to int and accept the resulting 2. C Parse under the whole-number contract or explicitly validate the fractional part before conversion. D Convert it to float before checking the range.
Truncation and display formatting can conceal a fractional value; validation must implement the actual quantity requirement.
Show answer
An appointment system receives a local time that occurs twice during a clock change. What should it do?
A Assume the first parsed value is always the user's intent. B Add exactly twenty-four hours before validation. C Remove the time zone to avoid the ambiguity. D Detect the ambiguity and apply a documented choice or ask for an offset.
The repeated clock reading represents two possible instants, so the application must resolve the ambiguity intentionally.
Show answer
A user-selected literal prefix must be inserted into a regex. What should the implementation do?
A Escape the literal fragment and retain input and execution bounds. B Enable IgnoreCase to neutralize every special character. C Add a wildcard before the prefix. D Insert it directly because strings cannot contain regex syntax.
Regex.Escape prevents a literal fragment from changing pattern syntax; separate resource limits remain necessary.
Show answer
A report loops over thousands of rows and appends text. Which design is appropriate?
A Share one global builder across all concurrent requests. B Use an operation-owned builder, bound output, and convert to a string when complete. C Call ToString after every append to make the builder immutable. D Treat the builder's capacity as a maximum input length.
Local ownership and one final conversion suit incremental construction; capacity is not a validation limit.
Show answer
A compiler cannot find Shop.Core.PriceCalculator. Which investigation is most useful?
A Copy the generated bin directory into the source folder. B Install the first package with Price in its name. C Check source inclusion, project reference, public visibility and namespace. D Add global using directives for every known namespace.
These checks address the actual source, dependency and accessibility boundaries without hiding the problem.
Show answer
An inventory dictionary should ignore code capitalization using an ordinal rule. Which design is coherent?
A Lowercase only the keys at insertion with the current culture. B Normalize insertion with one comparer and lookup with a different culture-based rule. C Store each capitalization as a separate product. D Construct the dictionary with StringComparer.OrdinalIgnoreCase.
A collection comparer applies the same equality and hashing policy to insertion and lookup.
Show answer
A helper intentionally supplies a label for missing text. Which contract is clear?
A Accept string?, handle null explicitly, and receive the fallback as an argument. B Use a hidden global fallback that changes between callers. C Add an extension on object and assume every value is a string. D Accept non-null string, then dereference it before checking.
The nullable signature and explicit fallback make the presentation policy visible and testable.
Show answer
A generated sequence reads changing external data. A caller counts it and then loops over it. What concern should be reviewed?
A Count permanently freezes all later values. B The two traversals can repeat work and observe different data. C The second traversal is automatically free. D IEnumerable guarantees exactly one underlying traversal.
IEnumerable does not guarantee a stored snapshot or inexpensive repeat enumeration.
Show answer
A resource has asynchronous cleanup that must complete before proceeding. Which form expresses that contract?
A Synchronous using, assuming it awaits any available asynchronous cleanup. B Calling DisposeAsync and ignoring its result. C await using inside an async-capable method. D Invoking DisposeAsync without awaiting completion before using the dependent result.
Await using awaits IAsyncDisposable cleanup at scope exit.
Show answer
Why is List<Dog> not assignable to List<Animal>?
A Dogs cannot be read as animals. B Every generic class automatically supports covariance whenever its argument is a reference type. C Variance is permitted even when the same type parameter is used for both reads and writes. D The widened mutable list would allow inserting an incompatible Animal.
Mutation introduces an input position that makes the proposed covariance unsafe.
Show answer
A reflection-heavy library is published with trimming. What should be checked?
A Analysis warnings, preserved-member requirements and the actual published behavior. B Only the untrimmed development run. C Only whether the library compiles without errors before trimming. D Only whether reflection works in an untrimmed unit-test process.
Dynamic discovery can require explicit preservation and deployment-mode verification.
Show answer
A job identifier must be registered only if absent. Which operation fits?
A Call ContainsKey, then assign through the indexer. B Use TryAdd and act on its returned success result. C Mark the dictionary reference volatile. D Lock an unrelated newly created object for each call.
TryAdd performs the intended conditional collection transition atomically.
Show answer
A singleton coordinator needs one scoped worker per job. Which design fits?
A Disable validation and keep one root-resolved worker. B Build a new root provider inside each worker method. C Create and dispose an explicit scope around each job. D Store each scoped worker in a global list after disposal.
An explicit per-job scope preserves the worker's lifetime while the coordinator remains singleton.
Show answer
Which statement about development user secrets is accurate?
A They are an encrypted production vault by definition. B They make logging credentials safe. C They automatically rotate every credential. D They keep development values outside the project but require a separate production policy.
User secrets are a development storage convenience, not a complete production secret-management system.
Show answer
An import exceeds its supported batch limit. Which event is most useful and safe?
A A stable rejection template with row count, maximum and a safe batch identifier. B The full input file and connection string. C A success message after rejecting the batch. D A different dynamically assembled template for every row.
Bounded selected context explains the outcome without leaking unrelated sensitive data.
Show answer
A 404 is a normal missing-item outcome for an API. Which implementation fits?
A Parse every response as a successful item. B Map 404 explicitly and validate other statuses before parsing. C Retry forever until a 200 arrives. D Convert every status into an empty item.
The client should implement the documented status contract rather than treating all responses alike.
Show answer
A read-only catalog endpoint needs only product codes under a price limit. Which query design fits?
A Materialize every product first, then filter in application memory. B Share one singleton context between all concurrent requests. C Filter and project before bounded materialization, using no tracking when updates are unnecessary. D Track every returned entity so it cannot change elsewhere.
The provider can reduce returned data, and read-only results need not accumulate tracking state.
Show answer
An order update includes OwnerSubject in its request body. What should the server use for ownership authorization?
A The token payload before validation. B The body field alone. C A valid token's unrelated permission claim without checking the stored resource owner. D The stored resource owner compared with the validated principal's stable subject.
Ownership evidence must come from trusted stored state and an authenticated identity, not caller-controlled claims.
Show answer
No exercises match those filters.