C#143 exercises

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.

Score0/ 143

1Introduction

Read the lesson
Fill in the blankseasyIntroduction

Complete the code to print a message on its own line.

Console.("Good morning");
Multiple choiceeasyIntroduction

What ends most statements in C#?

Predict the outputmediumIntroduction

What does this print?

Console.Write("A");
Console.Write("B");
Console.WriteLine("C");
Multiple choicemediumIntroduction

Which command builds and runs a C# project?

Multiple choicehardIntroduction

What do top-level statements in Program.cs replace?

2Variables & Types

Read the lesson
Fill in the blankseasyVariables & Types

Complete the declaration to store a price exactly.

 price = 4.50m;
Predict the outputeasyVariables & Types

What does this print?

int x = (int)8.9;
Console.WriteLine(x);
Multiple choicemediumVariables & Types

What type does var n = 5.0; give n?

Predict the outputmediumVariables & Types

What does this print?

bool ok = int.TryParse("12a", out int n);
Console.WriteLine($"{ok} {n}");
Multiple choicehardVariables & Types

Why does double total = 0.1 + 0.2; not equal 0.3 exactly?

3Operators & Math

Read the lesson
Fill in the blankseasyOperators & Math

Complete the code to add 10 to points.

int points = 5;
points  10;
Predict the outputeasyOperators & Math

What does this print?

Console.WriteLine(17 % 5);
Predict the outputmediumOperators & Math

What does this print?

int x = 5;
int y = x++ + 1;
Console.WriteLine($"{x} {y}");
Multiple choicemediumOperators & Math

Why is name != null && name.Length > 0 safe when name is null?

Multiple choicehardOperators & Math

What does Math.Round(3.5) return by default?

Fill in the blankseasyStrings

Complete the code so the message includes the name.

string name = "Sam";
Console.WriteLine("Hi {name}");
Predict the outputeasyStrings

What does this print?

Console.WriteLine("banana".IndexOf("n"));
Predict the outputmediumStrings

What does this print?

string s = "a,b,,c";
Console.WriteLine(s.Split(',').Length);
Multiple choicemediumStrings

What does $"{9.5:F2}" produce?

Multiple choicehardStrings

Why is StringBuilder faster than += when building a long string in a loop?

5Input & Output

Read the lesson
Fill in the blankseasyInput & Output

Complete the line that reads what the user types.

string? text = Console.();
Multiple choiceeasyInput & Output

What type does Console.ReadLine return?

Predict the outputmediumInput & Output

The user types 42 . What does this print?

bool ok = int.TryParse(Console.ReadLine(), out int n);
Console.WriteLine(ok ? n + 1 : -1);
Multiple choicemediumInput & Output

What does Console.ReadLine() ?? "" do?

Multiple choicehardInput & Output

How do you pass "data.csv" to args[0]?

6if & switch

Read the lesson
Fill in the blankseasyif & switch

Complete the condition so the second message runs when the first condition is false.

if (age >= 18)
{
    Console.WriteLine("Adult");
}

{
    Console.WriteLine("Under 18");
}
Predict the outputeasyif & switch

What does this print?

int stock = 0;
Console.WriteLine(stock > 0 ? "Available" : "Sold out");
Predict the outputmediumif & switch

What does this print?

int n = 15;
string r = n switch { < 10 => "low", < 20 => "mid", _ => "high" };
Console.WriteLine(r);
Multiple choicemediumif & switch

What does _ mean in a switch expression?

Multiple choicehardif & switch

What does x is >= 1 and <= 5 check?

Fill in the blankseasyLoops

Complete the loop so it visits every name.

string[] names = { "Ana", "Ben" };
 (string name in names)
{
    Console.WriteLine(name);
}
Predict the outputeasyLoops

How many lines does this print?

for (int i = 0; i < 4; i++)
{
    Console.WriteLine(i);
}
Predict the outputmediumLoops

What does this print?

int sum = 0;
for (int i = 1; i <= 10; i++)
{
    if (i % 2 == 0) continue;
    sum += i;
}
Console.WriteLine(sum);
Multiple choicemediumLoops

Which loop always runs its body at least once?

Multiple choicehardLoops

Why does removing items from a list inside foreach fail?

Fill in the blankseasyMethods

Complete the method so it returns the doubled value.

int Twice(int n)
{
     n * 2;
}
Predict the outputeasyMethods

What does this print?

string Greet(string name = "friend") => $"Hi {name}";
Console.WriteLine(Greet());
Multiple choicemediumMethods

What return type does a method that returns nothing have?

Predict the outputmediumMethods

What does this print?

int Add(int a, int b) => a + b;
double Add(double a, double b) => a + b + 0.5;
Console.WriteLine(Add(1, 2));
Multiple choicehardMethods

What must a method with an out parameter do?

Fill in the blankseasyArrays

Complete the code to print the number of items.

int[] nums = { 4, 8, 15 };
Console.WriteLine(nums.);
Predict the outputeasyArrays

What does this print?

string[] colours = { "red", "green", "blue" };
Console.WriteLine(colours[1]);
Predict the outputmediumArrays

What does this print?

int[] a = { 1, 2, 3 };
int[] b = a;
b[0] = 99;
Console.WriteLine(a[0]);
Multiple choicemediumArrays

What does new bool[3] contain?

Multiple choicehardArrays

What does arr[1..^1] give for { 10, 20, 30, 40 }?

10Lists & Dictionaries

Read the lesson
Fill in the blankseasyLists & Dictionaries

Complete the code to add an item to the end of the list.

var names = new List<string>();
names.("Ada");
Predict the outputeasyLists & Dictionaries

What does this print?

var nums = new List<int> { 5, 6, 7 };
nums.RemoveAt(0);
Console.WriteLine(nums[0]);
Multiple choicemediumLists & Dictionaries

What happens when you read dict["missing"] for a key that doesn't exist?

Predict the outputmediumLists & Dictionaries

What does this print?

var set = new HashSet<int> { 1, 2, 2, 3, 3, 3 };
Console.WriteLine(set.Count);
Multiple choicehardLists & Dictionaries

Why is looking up a key in a Dictionary faster than searching a List?

11Classes & Objects

Read the lesson
Fill in the blankseasyClasses & Objects

Complete the line to create a new Car object.

var car =  Car();
Multiple choiceeasyClasses & Objects

What is the default access level of a class member in C#?

Predict the outputmediumClasses & Objects

What does this print?

class Box { public int Size; }
var a = new Box { Size = 1 };
var b = a;
b.Size = 5;
Console.WriteLine(a.Size);
Multiple choicemediumClasses & Objects

What does a static field belong to?

Multiple choicehardClasses & Objects

Why keep fields private and change them through methods?

12Properties & Constructors

Read the lesson
Fill in the blankseasyProperties & Constructors

Complete the property so it can be read and written.

public string Title { get; ; }
Multiple choiceeasyProperties & Constructors

What is the name of a constructor?

Predict the outputmediumProperties & Constructors

What does this print?

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; }
Multiple choicemediumProperties & Constructors

What does { get; private set; } allow?

Multiple choicehardProperties & Constructors

What does the required modifier do?

13Inheritance & Polymorphism

Read the lesson
Fill in the blankseasyInheritance & Polymorphism

Complete the declaration so Cat inherits from Animal.

class Cat  Animal
{
}
Multiple choiceeasyInheritance & Polymorphism

How many base classes can a C# class inherit from?

Predict the outputmediumInheritance & Polymorphism

What does this print?

A obj = new B();
Console.WriteLine(obj.Name());
class A { public virtual string Name() => "A"; }
class B : A { public override string Name() => "B"; }
Multiple choicemediumInheritance & Polymorphism

What does : base(name) on a constructor do?

Multiple choicehardInheritance & Polymorphism

What must a non-abstract class do when it inherits an abstract method?

14Interfaces

Read the lesson
Fill in the blankseasyInterfaces

Complete the declaration of the interface.

 IPrintable
{
    void Print();
}
Multiple choiceeasyInterfaces

By convention, what do C# interface names start with?

Multiple choicemediumInterfaces

How many interfaces can a class implement?

Predict the outputmediumInterfaces

What does this print?

IGreeter g = new Polite();
Console.WriteLine(g.Hello());
interface IGreeter { string Hello(); }
class Polite : IGreeter { public string Hello() => "Good day"; }
Multiple choicehardInterfaces

What does using var conn = OpenConnection(); guarantee?

15Structs & Records

Read the lesson
Fill in the blankseasyStructs & Records

Complete the line to make a copy of the record with a new price.

var sale = item  { Price = 5m };
Multiple choiceeasyStructs & Records

Which of these is a value type?

Predict the outputmediumStructs & Records

What does this print?

var a = new P(1, 2);
var b = new P(1, 2);
Console.WriteLine(a == b);
record P(int X, int Y);
Predict the outputmediumStructs & Records

What does this print?

var s = new S { V = 1 };
var t = s;
t.V = 9;
Console.WriteLine(s.V);
struct S { public int V; }
Multiple choicehardStructs & Records

What does the compiler generate for record Point(int X, int Y);?

Fill in the blankseasyEnums

Complete the declaration of the enum.

 Direction { North, East, South, West }
Predict the outputeasyEnums

What does this print?

Console.WriteLine((int)Color.Blue);
enum Color { Red, Green, Blue }
Multiple choicemediumEnums

Which method converts user text to an enum without throwing?

Predict the outputmediumEnums

What does this print?

var p = Perm.Read | Perm.Write;
Console.WriteLine(p.HasFlag(Perm.Write));
[Flags] enum Perm { None = 0, Read = 1, Write = 2 }
Multiple choicehardEnums

Why should flags enum values be powers of two?

17Exceptions

Read the lesson
Fill in the blankseasyExceptions

Complete the block that always runs, whether or not an exception happens.

try { Work(); }
catch (Exception) { Console.WriteLine("Failed"); }
 { Console.WriteLine("Done"); }
Predict the outputeasyExceptions

What does this print?

try
{
    Console.WriteLine("A");
    throw new Exception("x");
    Console.WriteLine("B");
}
catch { Console.WriteLine("C"); }
Multiple choicemediumExceptions

Why put specific catch blocks before catch (Exception)?

Multiple choicemediumExceptions

What's the difference between throw; and throw ex; in a catch block?

Multiple choicehardExceptions

When should you catch Exception, the base type of all exceptions?

Fill in the blankseasyGenerics

Complete the method so it works for any type.

T Identity(T value) => value;
Predict the outputeasyGenerics

What does this print?

var box = new Box<string>("hi");
Console.WriteLine(box.Value.Length);
class Box<T>(T value) { public T Value { get; } = value; }
Multiple choicemediumGenerics

What does where T : new() allow inside the generic code?

Predict the outputmediumGenerics

What does this print?

Console.WriteLine(Default<int>() + 1);
T Default<T>() => default!;
Multiple choicehardGenerics

Why is List<int> faster than List<object> holding the same numbers?

Fill in the blankseasyLINQ

Complete the query to keep only prices above 10.

var expensive = prices.(p => p > 10);
Predict the outputeasyLINQ

What does this print?

var nums = new[] { 1, 2, 3, 4 };
Console.WriteLine(nums.Select(n => n * 10).Sum());
Multiple choicemediumLINQ

What does FirstOrDefault return when nothing matches a list of objects?

Predict the outputmediumLINQ

What does this print?

var words = new[] { "apple", "avocado", "banana", "blueberry", "cherry" };
var groups = words.GroupBy(w => w[0]);
Console.WriteLine(groups.Count());
Multiple choicehardLINQ

What does deferred execution mean in LINQ?

20Delegates & Lambdas

Read the lesson
Fill in the blankseasyDelegates & Lambdas

Complete the lambda so it doubles its input.

Func<int, int> twice = x  x * 2;
Multiple choiceeasyDelegates & Lambdas

Which built-in delegate type returns nothing?

Predict the outputmediumDelegates & Lambdas

What does this print?

Func<int, int, int> f = (a, b) => a * b + 1;
Console.WriteLine(f(3, 4));
Predict the outputmediumDelegates & Lambdas

What does this print?

int x = 1;
Func<int> get = () => x;
x = 10;
Console.WriteLine(get());
Multiple choicehardDelegates & Lambdas

Why can't outside code raise a class's event directly?

21async & await

Read the lesson
Fill in the blankseasyasync & await

Complete the line to wait for the task's result.

int count =  CountUsersAsync();
Multiple choiceeasyasync & await

What should an async method that returns no value return?

Predict the outputmediumasync & await

Each call takes about 2 seconds. Roughly how long does this take?

await Task.WhenAll(WorkAsync(), WorkAsync(), WorkAsync());
Multiple choicemediumasync & await

Why is Task.Delay better than Thread.Sleep in async code?

Multiple choicehardasync & await

Which exception signals that an operation was cancelled through a CancellationToken?

22Files & JSON

Read the lesson
Fill in the blankseasyFiles & JSON

Complete the line to read the whole file into a string.

string text = File.("notes.txt");
Multiple choiceeasyFiles & JSON

Which method adds text to the end of a file without removing what's there?

Multiple choicemediumFiles & JSON

Why use Path.Combine instead of joining strings with a slash?

Predict the outputmediumFiles & JSON

What does this print?

var json = JsonSerializer.Serialize(new { Name = "Ada", Age = 36 });
Console.WriteLine(json);
Multiple choicehardFiles & JSON

Why is File.ReadLines better than File.ReadAllLines for a very large file?

23Nullable & Patterns

Read the lesson
Fill in the blankseasyNullable & Patterns

Complete the declaration so the variable may hold null.

string middleName = null;
Predict the outputeasyNullable & Patterns

What does this print?

string? s = null;
Console.WriteLine(s?.Length ?? -1);
Multiple choicemediumNullable & Patterns

What does x ??= 10; do?

Predict the outputmediumNullable & Patterns

What does this print?

var p = new Pt(2, 5);
Console.WriteLine(p is { X: > 0, Y: > 4 });
record Pt(int X, int Y);
Multiple choicehardNullable & Patterns

Does the null-forgiving operator ! prevent a NullReferenceException?

24Unit Testing

Read the lesson
Fill in the blankseasyUnit Testing

Complete the attribute that marks a simple test in xUnit.

]
public void Adds() => Assert.Equal(4, 2 + 2);
Multiple choiceeasyUnit Testing

Which command runs every test in a solution?

Multiple choicemediumUnit Testing

What does [Theory] with three [InlineData] rows produce?

Predict the outputmediumUnit Testing

Will this test pass?

[Fact]
public void Divide_ByZero_Throws() =>
    Assert.Throws<DivideByZeroException>(() => { int z = 0; _ = 10 / z; });
Multiple choicehardUnit Testing

Why make classes depend on interfaces like IClock rather than DateTime.Now?

25Minimal APIs

Read the lesson
Fill in the blankseasyMinimal APIs

Complete the line to handle GET requests to /hello.

app.("/hello", () => "Hello!");
Multiple choiceeasyMinimal APIs

Which status code means a new resource was created?

Multiple choicemediumMinimal APIs

Where does int page come from in app.MapGet("/search", (string q, int page) => ...)?

Predict the outputmediumMinimal APIs

A request is sent to /products/abc. What happens with this route?

app.MapGet("/products/{id:int}", (int id) => id);
Multiple choicehardMinimal APIs

Which service lifetime is usually right for a database context?

26Conversions and Culture

Read the lesson
Multiple choicemediumConversions and Culture

An imported value of 2.9 must be rejected because quantities are whole numbers. Which approach satisfies the rule?

27Dates and Times

Read the lesson
Multiple choicemediumDates and Times

An appointment system receives a local time that occurs twice during a clock change. What should it do?

28Regular Expressions

Read the lesson
Multiple choicemediumRegular Expressions

A user-selected literal prefix must be inserted into a regex. What should the implementation do?

29Unicode and Encoding

Read the lesson
Multiple choicemediumUnicode and Encoding

A report loops over thousands of rows and appends text. Which design is appropriate?

30Projects and NuGet

Read the lesson
Multiple choicemediumProjects and NuGet

A compiler cannot find Shop.Core.PriceCalculator. Which investigation is most useful?

31Equality and Hashing

Read the lesson
Multiple choicemediumEquality and Hashing

An inventory dictionary should ignore code capitalization using an ordinal rule. Which design is coherent?

32Extension Methods

Read the lesson
Multiple choicemediumExtension Methods

A helper intentionally supplies a label for missing text. Which contract is clear?

33Iterators and Yield

Read the lesson
Multiple choicemediumIterators and Yield

A generated sequence reads changing external data. A caller counts it and then loops over it. What concern should be reviewed?

34Disposal and Ownership

Read the lesson
Multiple choicemediumDisposal and Ownership

A resource has asynchronous cleanup that must complete before proceeding. Which form expresses that contract?

35Generic Variance

Read the lesson
Multiple choicemediumGeneric Variance

Why is List<Dog> not assignable to List<Animal>?

36Attributes and Reflection

Read the lesson
Multiple choicemediumAttributes and Reflection

A reflection-heavy library is published with trimming. What should be checked?

37Thread Safety

Read the lesson
Multiple choicemediumThread Safety

A job identifier must be registered only if absent. Which operation fits?

38DI Lifetimes

Read the lesson
Multiple choicemediumDI Lifetimes

A singleton coordinator needs one scoped worker per job. Which design fits?

39Configuration and Options

Read the lesson
Multiple choicemediumConfiguration and Options

Which statement about development user secrets is accurate?

40Structured Logging

Read the lesson
Multiple choicemediumStructured Logging

An import exceeds its supported batch limit. Which event is most useful and safe?

41HTTP Clients

Read the lesson
Multiple choicemediumHTTP Clients

A 404 is a normal missing-item outcome for an API. Which implementation fits?

42Entity Framework Core

Read the lesson
Multiple choicemediumEntity Framework Core

A read-only catalog endpoint needs only product codes under a price limit. Which query design fits?

43Authentication and Authorization

Read the lesson

An order update includes OwnerSubject in its request body. What should the server use for ownership authorization?

Next steps