C# Quiz: Test Your C# Knowledge
Pick how many questions you want, choose a difficulty and go. You'll see why each answer is right or wrong, then you can retry to beat your score.
What platform does C# run on?
- The JVM
- Node.js
- .NET
- Python
Which game engine uses C# for scripting?
- Unity
- Unreal Engine
- Godot only
- GameMaker
Is C# case-sensitive?
- No
- Only for strings
- Only on Linux
- Yes, Console and console are different names
What naming style do C# methods and classes use?
- camelCase
- PascalCase
- snake_case
- kebab-case
What does "statically typed" mean?
- Every variable has a type that the compiler checks before the program runs
- Variables never change
- Code runs without compiling
- Only static methods are allowed
Which type holds true or false?
- bool
- int
- string
- char
What does const mean?
- The variable is private
- The value is fixed and can never change
- The variable can hold any type
- The value is calculated later
Which literal is a char?
- "A"
- A
- 'A'
A
Does var make a variable dynamically typed?
- Yes, it can hold any type later
- Only for strings
- No, the compiler infers one fixed type from the value
- Only inside methods
Which method converts text to an int without throwing on invalid input?
- int.Parse
- Convert.ToInt32
- (int)text
- int.TryParse
What is
10 / 4in C# when both are ints?- 2.5
- 3
- 2
- 2.0
What does the || operator mean?
- And
- Not
- Equal
- Or
What range does
Random.Shared.Next(1, 11)return?- 0 to 10
- 1 to 11
- 0 to 11
- 1 to 10
What does
Math.Clamp(-5, 0, 10)return?- -5
- 0
- 10
- 5
Which expression checks whether n is even?
- n / 2 == 0
- n % 2 == 1
- n % 2 == 0
- n == 2
What does
"Hello".Lengthreturn?- 4
- 5
- 6
- "Hello"
How do you compare two strings ignoring case?
- a == b
- string.Equals(a, b, StringComparison.OrdinalIgnoreCase)
- a.Compare(b)
- a.ToUpper() = b
What does @ before a string literal do?
- Interpolates values
- Makes it a char
- Makes it constant
- Makes a verbatim string where backslashes are literal
What does
"Codevra".Substring(4)return?- "Code"
- "evra"
- "vra"
- "v"
What does
"abc"[^1]give?- 'c'
- 'a'
- 'b'
- An error
Which method prints without moving to a new line?
- Console.WriteLine
- Console.Write
- Console.Print
- Console.Out
Why use int.TryParse rather than int.Parse for user input?
- It's shorter
- It accepts decimals
- It reads from the console automatically
- It returns false for invalid text instead of throwing an exception
What does Console.ReadKey do?
- Reads a single key press
- Reads a whole line
- Reads a file
- Returns the last key typed earlier
What does
answer is "y" or "yes"check?- That answer contains y
- That answer is a bool
- That answer equals "y" or equals "yes"
- Nothing, it's invalid
How do you restore the console's normal colour after changing it?
- Console.Clear()
- Console.ResetColor()
- Console.ForegroundColor = null
- Restart the program
What type must an if condition be?
- int
- string
- bool
- Any type
Which keyword ends a section in a switch statement?
- stop
- end
- exit
- break
What does a switch expression produce?
- Nothing
- A value
- A loop
- A method
What is a guard clause?
- A security feature
- An early check that returns from a method when a case is invalid
- A try block
- A type of loop
In an if, else if chain, how many blocks run?
- All true ones
- Always exactly two
- The last true one
- At most one: the first whose condition is true
What does break do inside a loop?
- Exits the loop immediately
- Skips one repetition
- Restarts the loop
- Pauses the program
What does continue do?
- Ends the program
- Exits all loops
- Repeats the same repetition
- Skips the rest of the current repetition and starts the next
Which condition safely loops over every index of an array arr?
- i <= arr.Length
- i < arr.Length - 1
- i != arr.Length + 1
- i < arr.Length
Which loop is best when you don't know how many repetitions you'll need?
- for
- while
- foreach
- None
How many times does the inner line run?
for (i = 0; i < 3; i++) for (j = 0; j < 4; j++) count++;- 12
- 7
- 3
- 4
What are the values passed to a method called?
- Parameters
- Returns
- Arguments
- Variables
What is method overloading?
- Several methods with the same name but different parameters
- Calling a method too often
- A method that calls itself
- A method with too many lines
What does
=>mean inint Square(int x) => x * x;?- A comparison
- A lambda stored in a variable
- A pointer
- The method body is a single expression whose value is returned
How can a method return two values?
- It can't
- Use two return statements
- Return a tuple such as (int, string), or use out parameters
- Return void
What does params allow?
- Passing any number of arguments, which arrive as an array
- Optional arguments only
- Named arguments
- Generic types
What index does the first item of an array have?
- 1
- -1
- It depends
- 0
Can an array change size after it's created?
- Yes, with Add
- No, its size is fixed; Array.Resize creates a new array
- Only arrays of strings
- Only in loops
What does Array.IndexOf return when the value isn't found?
- 0
- null
- An exception
- -1
What does
^1mean as an index?- The first item
- The last item
- Index 1
- An error
How do you get the number of rows in
int[,] grid?- grid.GetLength(0)
- grid.Length
- grid.Rows
- grid[0].Length
Which property gives the number of items in a List<T>?
- Count
- Length
- Size
- Total
Can a dictionary have two items with the same key?
- Yes
- Only for strings
- Only if the values differ
- No, keys are unique
Which collection is first in, first out?
- Stack<T>
- Queue<T>
- HashSet<T>
- Dictionary
What does List.RemoveAll(predicate) return?
- The new list
- true or false
- The number of items removed
- Nothing
What does HashSet.Add return when the item is already present?
- false
- true
- It throws
- The item
What is an object?
- A blueprint
- A method
- An instance of a class
- A namespace
What does
thisrefer to inside a method?- The current object
- The class
- The previous object
- The base class
What does == compare for two class instances by default?
- Their data
- Their ToString results
- Their types only
- Whether they are the same object (reference equality)
What happens when you call a method on a null reference?
- Nothing
- A NullReferenceException is thrown
- It returns null
- It creates the object
Why override ToString?
- To compare objects
- To make it static
- To make it a string
- To control how the object appears when printed or shown in the debugger
What does an init accessor allow?
- Setting the value only during object creation
- Changing the value any time
- Reading only
- Nothing
What is
valueinside a setter?- The old value
- The new value being assigned
- The property name
- A keyword for null
What does
: this("Guest")after a constructor do?- Calls the base class
- Creates a new object
- Calls another constructor of the same class first
- Sets a property called this
When is a computed property like
Total => Price * Qtycalculated?- Every time it's read
- Once, when the object is created
- Never
- Only in the constructor
Where are primary constructor parameters written?
- Inside a method called Primary
- In the Main method
- In attributes
- In brackets after the class name
Which keyword allows a method to be overridden?
- override
- sealed
- static
- virtual
Can you create an instance of an abstract class with new?
- No
- Yes
- Only in the same file
- Only with a primary constructor
What does sealed on a class mean?
- It can't have methods
- It's read-only
- No class can inherit from it
- It's abstract
What is polymorphism?
- Treating different derived objects through a base type, with each running its own version of a method
- Having many constructors
- Copying objects
- Using many namespaces
Which class does every C# class ultimately inherit from?
- Base
- object
- Class
- Root
Can you create an object directly from an interface with new?
- Yes
- Only with default methods
- No
- Only for generic interfaces
Which interface lets a type be used in foreach?
- IComparable
- IEnumerable<T>
- IDisposable
- IEquatable<T>
What's one advantage of interfaces over abstract classes?
- They're faster
- They can store fields
- They have constructors
- A class can implement many interfaces but inherit only one class
Why do interfaces make code easier to test?
- Tests run faster
- A fake implementation can replace a real database or service
- Interfaces can't fail
- They remove the need for tests
What does IComparable<T>.CompareTo return when this comes before other?
- true
- Zero
- A negative number
- A positive number
Is a record a class or a struct by default?
- A class (reference type)
- A struct
- Neither
- It depends on the properties
Can a struct inherit from another struct?
- Yes
- Only readonly structs
- No, but it can implement interfaces
- Only record structs
Does a with expression change the original record?
- No, it returns a new copy
- Yes
- Only for record structs
- Only if properties are set
Which is the best fit for an API response containing a product's name and price?
- A static class
- An enum
- A record
- An interface
Why should structs usually be small and immutable?
- The compiler requires it
- They're copied on every assignment, and mutable copies cause confusing bugs
- Large structs can't be created
- Immutable structs can be null
What number does the first enum value get by default?
- 1
- -1
- 0
- It has no number
What does
OrderStatus.Paid.ToString()return?- 1
- "Paid"
- "OrderStatus.Paid"
- null
How do you get every value of an enum?
- MyEnum.All
- MyEnum.Values()
- Enum.GetValues<MyEnum>()
- typeof(MyEnum).Count
Which operator combines flags?
- |
- &
- +
- ^
Why is reordering enum values risky when they're saved as numbers?
- It isn't
- The compiler forbids it
- Enums can't be saved
- Saved numbers would then map to different names, silently changing their meaning
Which keyword reports an error from your own code?
- catch
- error
- throw
- raise
Which exception does int.Parse("abc") throw?
- NullReferenceException
- FormatException
- OverflowException
- ArgumentException
What does
whenadd to a catch block?- A loop
- A filter: the catch only handles the exception if the condition is true
- A delay
- Logging
What should a custom exception class inherit from?
- object
- Error
- Exception (or a more specific exception type)
- IDisposable
Which is better for checking whether user input is a valid number?
- try int.Parse and catch FormatException
- Convert.ToInt32 in a try block
- A custom exception
- int.TryParse
What is T in
List<T>?- A variable
- A type parameter
- A method
- A namespace
How does C# usually know T in a generic method call?
- You must always write it
- It's always object
- From the return value only
- It infers it from the arguments
Which keyword adds constraints to a type parameter?
- when
- where
- if
- requires
Which constraint lets you call CompareTo on T?
- where T : class
- where T : new()
- where T : IComparable<T>
- where T : struct
What does default give for a reference type T?
- null
- 0
- An empty object
- An exception
Which method transforms each item into something else?
- Where
- OrderBy
- Select
- Any
Which method checks whether any item matches a condition?
- All
- Any
- Contains
- Count
What does GroupBy return?
- A dictionary
- A sorted list
- A single number
- A sequence of groups, each with a Key and its items
What does Single throw if two items match?
- An InvalidOperationException
- Nothing, it returns the first
- A FormatException
- A KeyNotFoundException
Which method flattens a list of orders, each with a list of items, into one list of items?
- Select
- GroupBy
- Join
- SelectMany
In
Func<string, int>, what is the return type?- int
- string
- void
- bool
What does
+=do with an event?- Raises it
- Subscribes a handler
- Removes all handlers
- Adds a number
What does Predicate<T> return?
- T
- void
- int
- bool
What is a closure?
- A lambda together with the variables it captures from surrounding code
- A finally block
- A sealed class
- A closed file
Why use
?.Invokewhen raising an event?- It's faster
- The event is null when there are no subscribers, and ?. avoids a NullReferenceException
- It runs handlers asynchronously
- It's required by the compiler
What naming convention do async methods follow?
- End with Async
- Start with Async
- Use lowercase
- End with Task
What does Task<T> represent?
- A thread
- A list of T
- A delegate
- An operation that will produce a T when it completes
What's wrong with calling .Result on a task?
- It blocks the thread and can cause deadlocks
- Nothing
- It returns null
- It runs the task twice
Which method finishes when the first of several tasks completes?
- Task.WhenAll
- Task.WhenAny
- Task.Run
- Task.Delay
How should HttpClient be used in an application?
- Create a new one for every request
- Only in Main
- Reuse one instance, or get clients from IHttpClientFactory
- Wrap each call in Task.Run
Which namespace contains File, Path and Directory?
- System.IO
- System.Text
- System.Files
- System.Data
What does JsonSerializer.Deserialize<T> do?
- Turns JSON text into an object of type T
- Writes JSON to a file
- Validates a file path
- Turns an object into JSON
What does WriteIndented = true change?
- Property names
- Numbers are rounded
- JSON is written over several indented lines, easier for people to read
- Null values are removed
What does Directory.CreateDirectory do if the folder already exists?
- Throws an exception
- Nothing; it simply returns
- Deletes and recreates it
- Creates a numbered copy
Which attribute maps a property to a different JSON name?
- [JsonIgnore]
- [Name("...")]
- [Serializable]
- [JsonPropertyName("...")]
What does
string?mean with nullable reference types enabled?- An optional parameter
- A string that can't be null
- A nullable int
- A string that may be null
What does
user?.Emailreturn when user is null?- null
- An empty string
- It throws
- "null"
Which pattern checks property values?
- Type pattern
- Property pattern { Name: value }
- List pattern
- Discard pattern
What does
..mean in a list pattern like [1, .., 9]?- A range of numbers
- Exactly two elements
- Any number of elements in between
- An error
Why is
is nullpreferred over== null?- It can't be changed by a custom == operator, so it's always a true null check
- It's faster to type
- == null doesn't compile
- It works only for strings
In Assert.Equal, which argument comes first?
- The actual value
- The expected value
- The message
- It doesn't matter
What are the three parts of the Arrange-Act-Assert pattern?
- Add, Assign, Approve
- Build, run, deploy
- Set up inputs, call the code under test, check the result
- Create, update, delete
What should an async test method return?
- void
- bool
- Task<bool>
- Task
What is a fake in testing?
- A test that always passes
- A broken build
- A simple implementation of a dependency that returns controlled data
- A copy of the database
Which assertion checks that awaited code throws an exception?
- Assert.Throws
- Assert.Fail
- Assert.Raises
- Assert.ThrowsAsync
What does returning a record from a minimal API handler send?
- XML
- Plain text
- JSON
- HTML
What does MapGroup("/products") do?
- Creates a database table
- Starts a new server
- Registers a service
- Groups endpoints under a shared route prefix
How does a handler get a registered service?
- new it up inside the handler
- Read a global variable
- Declare it as a handler parameter
- Use reflection
Which result should an endpoint return when the requested item doesn't exist?
- Ok(null)
- BadRequest()
- NoContent()
- NotFound()
Why accept a CancellationToken in an async endpoint?
- Work can stop when the client disconnects, saving server resources
- It's required
- It speeds up JSON
- It validates input
Which statement about an implicit int-to-float conversion is correct?
- The conversion is allowed, but some large integers lose precision.
- Every integer digit is always preserved.
- It parses the integer using the current culture.
- It always throws when the integer has more than six digits.
A CSV contract requires a period decimal separator regardless of the machine. What should the parser use?
- CurrentCulture with no documented style.
- An explicit invariant culture and permitted number styles.
- A global comma-to-period replacement.
- A checked cast from string to decimal.
Which type best represents a birthday without a clock time?
- TimeSpan
- DateOnly
- TimeOnly
- A local timestamp converted to UTC
What does an offset of +02:00 tell you about a DateTimeOffset value?
- The complete daylight-saving rules for its city.
- That its region never changes offset.
- The clock reading's offset from UTC at the represented instant.
- The operating system's local time-zone identifier.
A field must contain exactly two ASCII letters, a hyphen and four ASCII digits. Which detail matters?
- Removing anchors so a valid substring can be found.
- Using .* around the pattern to accept whitespace.
- Anchoring the whole input and specifying the intended character ranges.
- Replacing every character class with a wildcard.
What does RegexMatchTimeoutException establish?
- The input definitely fails the pattern.
- Every future match with this pattern will fail.
- The input contains no Unicode characters.
- Matching did not finish within the configured time budget.
The string A😀B has Length 4 in .NET. What is being counted?
- Four UTF-8 bytes.
- Four visible text elements.
- Four Unicode scalar values.
- Four UTF-16 code units.
What does UTF8Encoding(false, true) request?
- No generated BOM and exceptions for invalid encoding sequences.
- ASCII-only output with every emoji removed.
- Automatic detection of every source encoding.
- HTML escaping before byte conversion.
What does a using directive primarily do?
- Allows shorter names for types in a namespace.
- Downloads a NuGet package.
- Adds every solution project as a dependency.
- Changes a class library into an executable.
A console project and a library are in the same solution. What makes the library available to the console?
- A using directive for the library namespace without a project reference.
- A compatible explicit project reference.
- Building the solution once on the developer machine.
- A using directive alone.
Which implication must a correct equality and hashing implementation satisfy?
- Different values must always have different hashes.
- Equal values must have equal hashes under the same policy.
- Equal hashes must prove equality.
- Hash codes must remain identical across runtime versions.
Why should a HashSet key's equality-bearing fields remain stable?
- HashSet recomputes and relocates the stored key after every field assignment.
- HashSet automatically copies every field on insertion.
- Mutation can change its hash and invalidate the collection's lookup assumptions.
- A successful insertion guarantees every later lookup will find a mutated key.
What is a traditional C# extension method fundamentally?
- A private method inserted into another class at runtime.
- A virtual override discovered from the runtime type.
- A static method with an applicable this receiver parameter.
- A new instance member permanently added to the receiver type's metadata.
An applicable instance method and extension method share a name. Which behavior should you expect?
- The runtime selects whichever was imported last.
- The extension always replaces the instance method.
- Both methods execute in sequence.
- The instance member generally takes precedence.
When does the body of a typical IEnumerable iterator begin?
- At compilation.
- As soon as its method returns the sequence object.
- Only after every value has been requested.
- When the consumer first advances the enumerator.
Why put argument validation in a non-iterator wrapper?
- To reject invalid arguments immediately before deferred generation begins.
- To make validation inside the iterator execute when the sequence object is returned.
- To prevent foreach from disposing the enumerator.
- To force every sequence to be materialized.
What does using primarily guarantee?
- A disposal attempt when execution leaves the defined scope.
- Immediate reclamation of the object's managed memory.
- That Dispose can never throw.
- That the resource becomes safe to share across threads.
A wrapper receives a borrowed stream with leaveOpen true. What should disposal do?
- Close the stream because every parameter transfers ownership.
- Close the wrapper's own interface while preserving the caller-owned stream.
- Leave both the wrapper and stream usable.
- Force a collection to release the stream eventually.
Why can a producer of Dog be used as a producer of Animal?
- The conversion permits inserting any Animal into the producer.
- Every produced Dog satisfies the promised Animal output.
- All generic classes inherit from each other automatically.
- The runtime converts every Dog into a newly allocated Animal.
Which consumer can safely stand in for a consumer of Dog?
- A producer of Animal.
- A consumer that accepts only one particular Dog instance.
- A consumer able to accept any Animal.
- A mutable List<Animal> assigned to List<Dog>.
What is the role of a custom attribute?
- Automatically execute a method when the program starts.
- Make every property getter side-effect-free.
- Attach declarative metadata that a consumer can interpret.
- Give the class access to another type's private fields.
A reflection summary printer wants deterministic simple-property output. Which approach fits?
- Rely on unspecified member enumeration order.
- Read private and indexed properties without checks.
- Invoke every method before retrieving attributes.
- Filter public readable non-indexed instance properties and sort explicitly.
Why is checking stock and then decrementing it outside one boundary unsafe?
- An individually atomic field read makes the entire check-and-decrement transition atomic.
- Private visibility prevents other methods on the same object from overlapping.
- Parallel.For serializes updates to shared objects without synchronization.
- Another worker can interleave between the check and update.
Which action is unsuitable inside a GetOrAdd factory without an additional design?
- Charging a customer with an assumption that the factory runs exactly once.
- Computing a deterministic label.
- Constructing a repeatable candidate immutable value.
- Returning a value already permitted by the dictionary type.
Two resolutions of a scoped service occur within one scope. What is expected?
- The same scoped instance.
- Two unrelated instances in every case.
- The application's singleton instance automatically.
- A new scope for every constructor parameter.
A singleton directly retains a request-scoped database context. What is the concern?
- The context becomes transient automatically.
- A captive dependency outlives its intended scope and can be shared unsafely.
- The container copies it for every method call.
- Scope validation automatically turns the retained context into a thread-safe singleton.
Two providers define Retry:Attempts. Which value normally wins?
- The alphabetically first provider.
- The later provider's value for that key.
- The smallest numeric value.
- The options class default regardless of configuration.
A batch size of 5000 binds to int, but only 1–500 is supported. What is needed?
- Successful binding to int alone proves the value meets the feature's supported range.
- Moving the key into an environment variable without adding range validation.
- A feature validation rule before processing.
- Using a larger integer type while retaining no domain range check.
Which call preserves a named OrderId field?
- LogInformation($"Order {id} completed") exclusively.
- LogInformation(id.ToString()) exclusively.
- LogInformation("Order {OrderId} completed", id).
- Console.WriteLine("Order completed") exclusively.
What is a logging scope responsible for?
- Disposing every scoped DI service automatically.
- Encrypting all values passed to the logger.
- Choosing the application's authentication policy.
- Attaching contextual diagnostic values under a supporting provider.
Why does the main example dispose HttpResponseMessage?
- To change its status from 200 to 204.
- To force every pooled handler to be destroyed immediately.
- To erase the configured base address.
- To release response-owned resources at the operation boundary.
A POST times out after the server may have processed it. What must a retry policy consider?
- The operation's idempotency and possible duplicate effects.
- Only that the client can create a fresh request message for another attempt.
- Only whether the exception arose before the client received response headers.
- That timeouts prove the server made no change.
When does a tracked property change normally reach the database?
- When an appropriate SaveChanges operation succeeds.
- Immediately when its setter runs.
- Only when the context is garbage-collected.
- When AsNoTracking is added to the query.
What is EnsureCreated appropriate for in this guide?
- Replacing all production migration review.
- Initializing a deliberately disposable demonstration database.
- Updating every existing persistent schema automatically.
- Guaranteeing authorization for every queried row.
Which responsibility belongs to authentication?
- Deciding whether user-a owns order-7.
- Establishing a principal from validated trusted evidence.
- Granting every resource operation once a token has a valid signature.
- Treating every decoded claim as verified.
A valid authenticated token lacks a required permission. Which outcome is generally appropriate?
- HTTP 200 with unrestricted data.
- Mint a new token inside the endpoint.
- A forbid response, commonly HTTP 403.
- Skip the policy because the signature is valid.
About the C# quiz
This C# quiz covers every lesson in the course, from Console.WriteLine and variables to LINQ, async/await and minimal APIs. Many questions show a few lines of C# and ask what they print, because predicting output is the best way to check that you really understand how the language behaves. Others check vocabulary you'll meet in documentation and compiler errors, such as "value type", "interface", "lambda", "nullable" and "dependency injection".
If you're still in the beginner stage, choose Easy and a topic you've just finished, such as strings or loops. After the intermediate lessons, try Mixed with 10 questions to practise collections and classes together. Save Exam mode for the end of the course: it hides the answers until you finish, so it's an honest check of what you remember.
When you miss a question, read the explanation and revisit the lesson linked in your results. C# mistakes often come from small details: integer division, whether a type is a class or a struct, or when a LINQ query actually runs. Spotting them in a quiz makes them easy to avoid in real code.
The question bank holds 161 questions drawn from 43 C# lessons: 43 easy, 93 medium and 25 hard. Every time you start, the quiz picks a fresh random selection that matches your settings, so retaking it is a good way to practise. After each answer, or at the end in exam mode, you'll see why the right answer is right, and every question you miss links back to the lesson that teaches it.
What the C# quiz covers
Beginner
Intermediate
Advanced
Language and library reference
- 26C# Numeric Conversions and Culture
- 27C# Dates, Times and Time Zones
- 28C# Regular Expressions and Safe Matching
- 29C# StringBuilder, Unicode and Encoding
- 30C# Namespaces, Projects and NuGet
- 31C# Equality, Hashing and Comparers
- 32C# Extension Methods and API Design
- 33C# Iterators, Yield and Deferred Execution
- 34C# Disposal and Resource Ownership
- 35C# Generic Covariance and Contravariance
- 36C# Attributes and Reflection