C# Interview Questions
Every question has a short model answer and a link to the lesson example that shows it in code. Levels: F = Fresher (0-2 yrs), M = Mid (3-5 yrs), S = Senior (6-9 yrs), A = Architect / Lead (10+ yrs).
.NET platform
FWhat is the difference between the .NET SDK and the .NET runtime?concept
The runtime only runs .NET applications that are already built. The SDK (Software
Development Kit) contains the runtime plus the compiler and the dotnet command-line
tools to create, build, test, and publish applications. Developers install the SDK;
servers that only run the app need just the runtime.
MWhat is the difference between LTS and STS releases of .NET, and which would you choose for a production system?concept
LTS (Long Term Support) releases, such as .NET 10, get fixes and security patches for 3 years. STS (Standard Term Support) releases get them for 2 years. For a production system that must run for years, like a school system, choose LTS and plan upgrades from one LTS to the next.
FWhat is the CLR?concept
The Common Language Runtime is the part of .NET that runs your compiled code. It loads the IL, turns it into machine code with the JIT compiler, manages memory with the garbage collector, and handles exceptions.
FWhat is IL, and where is it stored?concept
IL (Intermediate Language) is what the C# compiler produces: a platform-neutral set of
instructions stored in the .dll file. The CLR turns it into machine code when the program runs.
FWhat is the difference between .NET and .NET Framework?concept
.NET Framework is the original, Windows-only platform; version 4.8.1 is the last, and it only gets maintenance. .NET (Core, then .NET 5 and later) is cross-platform, faster, and where all new development happens.
MWhat does JIT compilation mean, and why does .NET use it?concept
Just-In-Time compilation turns IL into machine code the first time each method runs, on the
machine that runs it. The same .dll can therefore run on Windows, Linux, and macOS, and the
JIT can optimize for the exact processor.
MWhat are top-level statements?concept
Code written directly in Program.cs without a class or Main method. The compiler generates
the Main method for you. Only one file in a project can have them, and they are ideal for
small programs and for the startup code of ASP.NET Core apps.
MWhat files does dotnet build produce, and what are they for?concept
In bin/Debug/net10.0: the .dll with your IL, an .exe launcher on Windows, a .pdb with
debug information, runtimeconfig.json naming the .NET version to use, and deps.json listing
dependencies. They are rebuilt every time and never committed.
SAn app runs on your laptop but fails to start on the server. How do you check whether it is a .NET version problem?scenario
Read the app's runtimeconfig.json to see which framework and version it needs, then run
dotnet --list-runtimes on the server. If the matching runtime is missing, install it, or
publish the app self-contained so it carries its own runtime.
Show a methodical check: what the app needs, what the server has, and the startup error message. Mention ASP.NET Core apps need the ASP.NET Core runtime, not just the base runtime.
SHow would you organize a .NET solution for a system with an API, shared logic, data access, and tests?design
One solution with projects in src (for example SchoolApp.Api, SchoolApp.Core,
SchoolApp.Data) and tests. Core holds models and rules with no dependencies, Data
references Core, and the API references both. Tests reference what they test.
Explain the dependency direction and why: Core must not depend on databases or web
frameworks, so it stays easy to test and reuse. Mention consistent naming and the .slnx format.
AFramework-dependent or self-contained deployment: how do you choose?design
Framework-dependent apps are small and use the runtime installed on the server, which the operations team patches. Self-contained apps carry their own runtime: larger, but independent of the server, and you must ship updates for security fixes yourself. Containers make this choice simpler, because the image includes the runtime.
Compare size, patching responsibility, and control over the version. Tie the decision to how the organization deploys: managed servers, customer machines, or containers.
Variables and data types
FWhich C# types match the SQL Server types INT, BIGINT, DECIMAL, NVARCHAR, DATE, and BIT?concept
int, long, decimal, string, DateOnly, and bool. Matching the types avoids
conversion errors and silently wrong values when data moves between the database and C#.
See the example · Lesson 31: Variables and data types · Permalink
FWhat does the var keyword do?concept
It lets the compiler work out the variable's type from the value on the right, for example
var tuition = 42000.00m; is a decimal. The type is still fixed at compile time; var only
saves typing, so use it when the type is obvious.
See the example · Lesson 31: Variables and data types · Permalink
FWhat is the difference between Parse and TryParse?concept
int.Parse converts text to a number and throws an exception if it cannot. int.TryParse
returns true or false and gives the number through an out parameter, so bad input never
crashes the program. Use TryParse for anything a person types.
See the example · Lesson 31: Variables and data types · Permalink
MWhy should money use decimal instead of double?concept
double stores numbers in binary, so most decimal fractions are approximations: 0.1 + 0.2
gives 0.30000000000000004. decimal stores base-10 numbers exactly, so sums of fees and
payments are exact. double is for measurements where tiny errors do not matter.
See the example · Lesson 31: Variables and data types · Permalink
MWhat is the difference between an implicit conversion and an explicit cast?concept
An implicit conversion is always safe and needs no code, such as int to long. An explicit
cast may lose data, so you must write it, such as (int)92.75m, which gives 92 because the
fraction is cut off, not rounded.
See the example · Lesson 31: Variables and data types · Permalink
MWhat is the difference between value types and reference types?concept
A value type variable holds the value itself (numbers, bool, char, DateOnly, structs).
A reference type variable holds a reference to an object stored elsewhere (string, classes,
arrays), and can be null. Copying a value type copies the value; copying a reference copies
only the reference.
See the example · Lesson 31: Variables and data types · Permalink
SSeveral invoices stay 'Partially paid' although families paid in full. What would you check first?scenario
The types used for money. If payments are summed in double, the balance can be a tiny
non-zero number such as 0.00000000003, so the status check never sees zero. Change money
variables to decimal, then correct the stuck invoices with a one-off script.
Connect the symptom to floating-point rounding, show how you would prove it (print the exact balance), fix the root cause, repair existing data, and prevent it with code review rules.
See the example · Lesson 31: Variables and data types · Permalink
SWhat happens when an integer overflows in C#, and how do you guard against it?concept
By default it wraps around silently: a byte at 255 plus 1 becomes 0. Choose types large
enough for the data, such as long for Ids that can grow, and use a checked block or the
project's overflow-checking setting where a wrong value would be dangerous, so overflow throws
an exception instead.
Show the default behavior, the risk (wrong totals or Ids), and two defenses: correct type sizing and checked arithmetic. Mention matching SQL types such as TINYINT and BIGINT.
See the example · Lesson 31: Variables and data types · Permalink
AHow would you keep C# types consistent with the database across a large team?design
Document one type mapping (for example DECIMAL to decimal, DATE to DateOnly), generate
or scaffold entity classes from the database where possible, and check mismatches in code
review and integration tests that round-trip real data.
Combine a written standard, tooling (scaffolding, analyzers), and tests. Mention that the database stays the source of truth for column types, as the SMS reference file does.
See the example · Lesson 31: Variables and data types · Permalink
Conditions and loops
FWhat is the difference between = and == in C#?concept
= assigns a value to a variable; == compares two values and returns true or false.
Writing if (mark = 33) does not compile in C#: error CS0029, because an int is not a bool.
See the example · Lesson 32: Conditions and loops · Permalink
FWhat are the four loops in C#, and when do you use each?concept
for repeats a known number of times with a counter; while repeats while a condition is
true and may run zero times; foreach visits each item in a collection; do...while runs at
least once and then checks its condition.
See the example · Lesson 32: Conditions and loops · Permalink
FWhat is the difference between break and continue?concept
break leaves the loop immediately. continue skips the rest of the current round and starts
the next one. In a switch statement, break ends each case.
See the example · Lesson 32: Conditions and loops · Permalink
MWhat is the difference between a switch statement and a switch expression?concept
A switch statement runs a block of code per case, with case, break, and default. A switch
expression produces a value from arms like >= 91 => "A1", checked from top to bottom, with _
for anything else. Switch expressions are shorter for mapping one value to another.
See the example · Lesson 32: Conditions and loops · Permalink
MWhat happens if a switch expression has no arm that matches the value?concept
The compiler warns with CS8509 that the switch is not exhaustive, and at run time an unmatched
value throws SwitchExpressionException. Always end with a _ discard arm.
See the example · Lesson 32: Conditions and loops · Permalink
MWhat does the ternary operator do, and when should you avoid it?concept
condition ? a : b returns a when the condition is true, otherwise b, as a one-line if.
Avoid it when the condition or values are complex, or when nested ternaries make the code hard
to read; use if or a switch expression instead.
See the example · Lesson 32: Conditions and loops · Permalink
SStudents with exactly 33 marks are shown as failed. How do you find and prevent this kind of bug?scenario
It is a boundary error: the condition uses > where the rule says "33 or more", so it should be
>=. Fix the operator, use a named constant such as PassMark, and add tests at the exact
boundaries (32, 33, 34) for every rule.
Explain the off-by-one cause, the fix, and the prevention: boundary-value tests and rules kept in one place. Mention re-checking data already produced with the wrong rule.
See the example · Lesson 32: Conditions and loops · Permalink
SA console tool that reads input in a loop hangs forever when run by a scheduled job. Why, and how do you fix it?scenario
When input comes from a file or a job, it can end; Console.ReadLine then returns null every
time, so a validation loop never gets valid input. Check for null and break, and design
batch tools to read arguments or files instead of prompting.
Show you think about every way a loop can end, including end of input. Mention timeouts and clear exit codes for tools run by schedulers.
See the example · Lesson 32: Conditions and loops · Permalink
AThe grading scale exists in SQL (fn_GetGrade) and in C#. How would you keep business rules consistent?design
Keep each rule in one authoritative place where possible, for example in a shared C# library used by every application, or in the database when reports depend on it. If a rule must exist twice, document it, test both against the same boundary cases, and change them together.
Discuss the trade-off between one source of truth and practical needs such as SQL reports, then the safety nets: shared test cases, code review checklists, and configuration-driven rules.
See the example · Lesson 32: Conditions and loops · Permalink
Arrays and strings
FWhat is an array, and where do its positions start?concept
A fixed-size collection of items of one type, stored under one name. Positions (indexes)
start at 0, so the last item is at Length - 1, also written ^1.
FWhat happens when you read an array position that does not exist?concept
The program throws IndexOutOfRangeException: Index was outside the bounds of the array.
For a six-item array, valid positions are 0 to 5.
FWhat does string interpolation do?concept
$"..." inserts values into text inside braces, such as $"Topper: {name}". Format
specifiers control the output: {average:F2} for two decimals, {serial:D5} for zero
padding, {name,-8} for column width.
MWhat does it mean that strings are immutable?concept
A string can never change after it is created. Methods such as Trim and ToUpper return a
new string, so name.Trim(); without assigning the result does nothing. Immutability makes
strings safe to share between threads and use as dictionary keys.
MWhen should you use StringBuilder instead of +?concept
When building text in a loop. Each += copies all the text so far into a new string, so the
cost grows with every line; StringBuilder appends to one buffer. In the SMS, 10,000 CSV
lines took about 620 ms with += and 2 ms with StringBuilder.
MHow do you compare two strings while ignoring upper and lower case?coding
string.Equals(a, b, StringComparison.OrdinalIgnoreCase), or methods like Contains and
StartsWith with a StringComparison argument. Avoid a.ToUpper() == b.ToUpper(), which
creates extra strings and can behave differently across cultures.
SAn export of all students sometimes times out for the largest school. What would you look for?scenario
How the file text is built. Building it with += in a loop has a cost that grows with the
square of the size, so small schools are fine and big ones time out. Switch to StringBuilder
or write lines straight to a stream, then measure with production-sized data.
Explain why the problem grows faster than the data, how you would prove it with a timer or profiler, and the fix. Mention streaming large files instead of holding them in memory.
SWhat are the risks of parallel arrays, and what is the better design?design
Two arrays kept in step, such as names and marks, break when one is sorted, filtered, or
resized without the other, so values attach to the wrong student. Keep related values together
in one object, such as a Student class or record, in one collection.
Show the failure concretely (sorting marks only), then the object-based design. Mention that this is the step from procedural code to object-oriented code.
AWhat should a team standardize about string handling in a multi-school, multi-language system?design
Ordinal, case-insensitive comparison for codes, user names, and emails; culture-aware
formatting only for text shown to people; a fixed format such as yyyy-MM-dd for files and
APIs; Unicode everywhere (NVARCHAR, UTF-8); and StringBuilder or streaming for large output.
Separate machine-facing text (codes, files, APIs: invariant and ordinal) from human-facing text (names, dates on screen: culture-aware). Give one bug each rule prevents.
Methods and parameters
FWhat is the difference between a parameter and an argument?concept
A parameter is the named input in the method's definition, such as decimal maxMarks. An
argument is the actual value passed in a call, such as 50m.
See the example · Lesson 34: Methods and parameters · Permalink
FWhat is an optional parameter?concept
A parameter with a default value, such as decimal maxMarks = 100m. Callers can leave it out,
and the default is used. Optional parameters must come after the required ones.
See the example · Lesson 34: Methods and parameters · Permalink
FWhat is method overloading?concept
Several methods with the same name but different parameter lists, such as
CalculateAttendancePercentage(int, int) and CalculateAttendancePercentage(string). The
compiler picks one from the argument types. A different return type alone is not enough.
See the example · Lesson 34: Methods and parameters · Permalink
MWhat is the difference between ref and out?concept
Both pass the caller's own variable. With ref, the variable must be assigned before the call,
and the method may read and change it. With out, it need not be assigned before, and the method
must assign it before returning. Both keywords appear in the definition and the call.
See the example · Lesson 34: Methods and parameters · Permalink
MWhat is the Try pattern?concept
A method named TryX that returns true or false for success and hands back the result
through an out parameter, like int.TryParse. It handles expected failures, such as bad
input, without exceptions.
See the example · Lesson 34: Methods and parameters · Permalink
MWhat does the params keyword do?concept
It lets callers pass any number of arguments, which C# collects into an array (or another
collection type), such as Average(92m, 85m, 67m). It must be the last parameter.
See the example · Lesson 34: Methods and parameters · Permalink
SA method takes nine parameters. What do you suggest in review?scenario
Too many parameters usually mean the method does too much or the values belong together. Split it into smaller methods, or group related values into an object, such as a request class with properties. Named arguments help readability in the meantime.
Name the smell, explain the risks (wrong order of arguments, hard to test), and offer refactorings: parameter objects, smaller methods, sensible defaults.
See the example · Lesson 34: Methods and parameters · Permalink
SThe same calculation exists in four screens and they disagree after a rule change. How do you fix and prevent it?scenario
Move the calculation into one well-named method with tests at its boundaries, and make every screen call it. Remove the copies. In reviews, treat duplicated business logic as a defect.
Cover the immediate fix (one method, tests), the data fix (correct anything produced wrongly), and prevention (shared library, review rule).
See the example · Lesson 34: Methods and parameters · Permalink
AWhen should an operation return a bool with out parameters, and when should it throw an exception?design
Use the Try pattern when failure is expected in normal use, such as parsing what a user typed.
Throw an exception when failure means something is truly wrong, such as a missing database
record that must exist. Many APIs offer both, like int.Parse and int.TryParse.
Tie the choice to how often failure happens and who handles it. Mention the cost of exceptions and the clarity of result types in larger systems.
See the example · Lesson 34: Methods and parameters · Permalink
Nullable types
FWhat is a nullable value type?concept
A value type with ?, such as int? or decimal?, that can hold either a value or null.
It has HasValue and Value. It maps to SQL columns that allow NULL, such as a mark for an
absent student.
FWhat do the ?? and ?. operators do?concept
?? returns the left value unless it is null, then the right value, like SQL's COALESCE.
?. accesses a member only if the object is not null, and returns null otherwise, instead of
throwing NullReferenceException.
FWhat causes a NullReferenceException?concept
Using a member, such as .Length or a method, on a variable that holds null. The message is
"Object reference not set to an instance of an object." Check for null first, or use ?. and ??.
MWhat are nullable reference types?concept
A compiler feature, turned on with <Nullable>enable</Nullable>, where string means "never
null" and string? means "may be null". The compiler warns (CS8600, CS8602, and others) when
code might use a null unsafely. It changes warnings, not run-time behavior.
MWhat does the null-forgiving operator ! do, and why is it risky?concept
x! tells the compiler to treat x as not null and silences the warning. It does nothing at
run time, so if x is null the program still crashes. Use it only when you truly know better
than the compiler, with a comment.
MHow should NULL marks be handled when calculating a class average?coding
Skip them: add only marks that are not null and divide by how many were counted, as SQL's AVG
does. Treating an absent student's null as 0 lowers the average unfairly: 395 ÷ 5 is 79, but
395 ÷ 6 is 65.83.
SThe parent app crashes for about one family in five. The log shows NullReferenceException. How do you find and fix it?scenario
Read the stack trace for the exact line, then find which value is null and why, for example a
guardian with no email. Fix it where the value is used, with a null check and a sensible fallback,
and make the type string? so the compiler warns at every other use.
Show the route from symptom to cause (stack trace, data pattern), the fix, and the prevention: nullable reference types on, warnings as errors, tests with missing data.
SHow do you introduce nullable reference types into a large existing codebase?design
Enable it project by project or file by file (#nullable enable), starting with shared core
code. Fix warnings in small batches, annotate public APIs first, and turn warnings into errors
once a project is clean, so it stays clean.
Emphasize a gradual, measurable rollout rather than enabling everything at once, and explain why public method signatures are the most valuable place to start.
AHow should 'no value' flow consistently from the database through the API to the client?design
Decide per field: NULL-able columns map to ? types in C#, and the API either returns null in
JSON or omits the field, documented in the API contract. Never turn missing data into fake values
such as 0 or empty strings, which clients cannot tell apart from real data.
Walk through each layer (database, data access, domain, API, client) and the rule at each. Mention consistency, documentation, and tests with missing data.
Exceptions and debugging
FWhat do try, catch, and finally do?concept
try holds code that might fail. catch runs when a matching exception is thrown in try.
finally always runs afterwards, success or failure, so it is used for cleanup.
See the example · Lesson 36: Exceptions and debugging · Permalink
FWhat happens when an exception is not caught anywhere?concept
It travels up through every calling method. If none catches it, the program stops and prints "Unhandled exception" with the exception type, message, and stack trace.
See the example · Lesson 36: Exceptions and debugging · Permalink
FWhat is a breakpoint, and what do F10 and F11 do?concept
A breakpoint (F9) pauses the program at a line so you can inspect variables. F10 steps over the current line; F11 steps into the method called on that line. The Locals and Call Stack windows show the values and the chain of calls.
See the example · Lesson 36: Exceptions and debugging · Permalink
MWhat is the difference between throw; and throw ex;?concept
throw; rethrows the current exception and keeps its original stack trace. throw ex; restarts
the stack trace from the rethrow, so the place where the error really happened is lost. The
analyzer warns with CA2200. Always use throw;.
See the example · Lesson 36: Exceptions and debugging · Permalink
MWhy does the order of catch blocks matter?concept
C# uses the first catch block whose type matches. If catch (Exception) comes first, it matches
everything, and later specific blocks never run. Put the most specific types first.
See the example · Lesson 36: Exceptions and debugging · Permalink
MWhen should you throw an exception, and when should you return a result such as false?concept
Return a result for expected situations, such as invalid user input, using the Try pattern. Throw when a rule is broken in a way the method cannot handle, such as a mark above the maximum reaching the save method. Exceptions are for exceptional cases, not normal flow.
See the example · Lesson 36: Exceptions and debugging · Permalink
SPayments sometimes go missing with no error anywhere. What would you suspect, and how would you investigate?scenario
A swallowed exception: an empty catch or one that logs nothing. Search for empty catch blocks
around the save path, use the debugger's Exception Settings to stop where exceptions are thrown,
and check database logs. Remove the empty catch so the real error appears, then fix the cause.
Show a structured investigation: reproduce, break on thrown exceptions, read logs, then fix the root cause. Add prevention: review rules against empty catch blocks, and logging with context.
See the example · Lesson 36: Exceptions and debugging · Permalink
SHow do you read a stack trace to find a bug?concept
Read the exception type and message first, then the at lines from the top, skipping framework
methods (System.) until you reach your own code. The first line in your code with a file and
line number is usually where to start; the lines below show who called it.
Walk through a real trace. Mention that release builds still give method names, that missing
.pdb files remove line numbers, and that throw ex; destroys the useful part.
See the example · Lesson 36: Exceptions and debugging · Permalink
ADesign an exception-handling strategy for a layered application with an API.design
Validate input early and return clear validation results. Let lower layers throw specific exceptions for broken rules, and do not catch what you cannot handle. Handle everything once, at the edge: global middleware logs the full exception with a correlation id and returns a safe, consistent error response, without exposing internal details.
Cover where exceptions are thrown, where they are caught (one place), what is logged, and what the client sees. Mention custom exception types for domain rules and mapping them to HTTP status codes.
See the example · Lesson 36: Exceptions and debugging · Permalink