.NET Developer interview questions
100 real questions with model answers and explanations for Junior .NET Developer candidates.
See a .NET Developer resume example →Practice with flashcards
Spaced repetition · Hunter Pass
Questions
C# is a programming language, .NET is the development platform and runtime ecosystem, and the CLR is the runtime that executes managed .NET code.
- The C# compiler normally produces Common Intermediate Language and assembly metadata.
- The CLR loads assemblies, verifies and compiles methods for execution, and provides runtime services.
- .NET also includes base libraries, an SDK, build tools, and application frameworks.
Why interviewers ask this: The interviewer is checking whether you distinguish the language, the platform, and its execution runtime.
The JIT compiler translates a method's intermediate language into native machine code when that method is needed at runtime.
- The generated code targets the current operating system and processor architecture.
- A method can be compiled on first use and then reused during the process lifetime.
- .NET also supports ahead-of-time options, but JIT compilation remains a core CLR execution model.
Why interviewers ask this: The interviewer is evaluating your basic understanding of how compiled C# reaches native execution.
A variable of a value type contains its value directly, while a variable of a reference type contains a reference to an object.
- Assigning a value type normally copies its contained value.
- Assigning a reference type copies the reference, so both variables can point to the same object.
- Structs, enums, and built-in numeric types are value types, while classes, arrays, and delegates are reference types.
Why interviewers ask this: A strong answer explains assignment semantics instead of reducing the distinction to stack versus heap.
A value type is stored inline wherever its containing storage lives, so its location is not always the stack.
- A local value may be stack-allocated when the runtime chooses that representation.
- A value-type field inside a class is stored as part of the class object on the managed heap.
- Boxing also places a copy of a value type inside a heap-allocated object.
Why interviewers ask this: The interviewer is checking whether your value-type model is based on semantics rather than an oversimplified storage rule.
A struct is a value type with copy-by-value semantics, while a class is a reference type with reference identity.
- Struct assignment copies the struct value, whereas class assignment copies a reference to the same instance.
- Structs cannot inherit from another class or struct, although they can implement interfaces.
- Small immutable data values are common struct candidates, while entities with identity and shared mutation usually fit classes.
Why interviewers ask this: The interviewer is evaluating whether you can connect the type category to copying, inheritance, and intended modeling.
Boxing converts a value type into an object or an interface reference by placing a copy of the value in a managed object.
- It can occur implicitly when a value type is assigned to object.
- Boxing allocates and copies, so repeated boxing can add memory and performance cost.
- Generic collections such as List<int> avoid boxing each integer, unlike older object-based collections.
Why interviewers ask this: A strong answer covers the conversion, allocation, and reason generics reduce boxing.
Unboxing extracts a value type from a boxed object through an explicit cast to the exact boxed value type.
- The object must contain a boxed value of the requested type.
- A null reference causes NullReferenceException, while an incompatible boxed type causes InvalidCastException.
- Unboxing does not perform ordinary numeric conversion, so a boxed int cannot be directly unboxed as long.
Why interviewers ask this: The interviewer is checking whether you understand that unboxing is an exact typed extraction, not a general cast.
C# provides numeric, Boolean, character, string, object, enum, tuple, array, and nullable forms among its common built-in type categories.
- Integral types differ by signedness and width, while float, double, and decimal serve different numeric needs.
- bool represents true or false, and char represents one UTF-16 code unit.
- string is a reference type whose instances are immutable.
Why interviewers ask this: The interviewer is evaluating basic type-system fluency and awareness of string and char semantics.
decimal is preferred for base-10 financial calculations where values such as monetary fractions should be represented predictably.
- double uses binary floating point and is usually faster with a much wider exponent range.
- Many decimal fractions cannot be represented exactly by double, which can produce visible rounding effects.
- Both types still require an explicit rounding policy for business rules.
Why interviewers ask this: A strong answer chooses numeric types by representation and domain requirements rather than size alone.
var asks the compiler to infer a local variable's static type from its initializer.
- The inferred type is fixed at compile time and does not make the variable dynamically typed.
- An initializer is required because the compiler needs an expression from which to infer the type.
- var is useful when the type is obvious or verbose, but an explicit type can communicate intent more clearly in other cases.
Why interviewers ask this: The interviewer is checking whether you distinguish compile-time inference from dynamic typing.
A nullable value type T? can represent either a value of T or no value.
- int? is shorthand for Nullable<int>.
- HasValue and Value expose its state, although Value throws if no value is present.
- The ?? operator supplies a fallback without manually checking HasValue.
Why interviewers ask this: The interviewer is evaluating whether you understand how value types can explicitly represent absence.
Nullable reference types are compile-time annotations and analysis that distinguish references intended to be non-null from those allowed to be null.
- string means non-null intent in an enabled nullable context, while string? permits null.
- The compiler reports warnings when code may dereference null or violate those annotations.
- The feature does not add runtime null checks or create a different CLR reference type.
Why interviewers ask this: A strong answer explains both the static safety benefit and the absence of new runtime semantics.
The operators ?., ??, and ! express different parts of null handling in C#.
- ?. stops member access and produces null when its receiver is null.
- ?? returns its right operand when the left operand is null.
- The postfix ! suppresses nullable warnings but performs no runtime validation and can hide a real null bug.
Why interviewers ask this: The interviewer is checking whether you can distinguish safe propagation, fallback selection, and warning suppression.
A constructor initializes a new class instance and establishes the state required by that instance.
- It has the class name, no return type, and can accept parameters.
- Constructors can be overloaded and can delegate to another constructor with this or to a base constructor with base.
- If no instance constructor is declared, the compiler may provide a parameterless one when the language rules allow it.
Why interviewers ask this: The interviewer is evaluating basic object construction and initialization knowledge.
These access modifiers control where a type or member can be accessed.
- public allows access wherever the containing type is accessible, while private limits access to the containing type.
- protected permits access through the declaring class and its derived classes.
- internal permits access from code in the same assembly.
Why interviewers ask this: The interviewer is checking whether you understand the common visibility boundaries used for encapsulation.
A field is storage declared directly on a type, while a property exposes accessor methods through field-like syntax.
- A property can validate, calculate, or restrict reading and writing through get, set, or init accessors.
- An auto-property lets the compiler create hidden backing storage.
- Public APIs generally prefer properties because their implementation can evolve without changing member access syntax.
Why interviewers ask this: A strong answer distinguishes direct storage from an encapsulated accessor-based contract.
A set accessor allows assignment after construction, while an init accessor limits assignment to object initialization and construction-related contexts.
- Both can be used by an object initializer.
- init helps create objects whose public state should not change after initialization.
- A readonly field is a different construct with its own assignment rules and is not a property accessor.
Why interviewers ask this: The interviewer is evaluating whether you understand basic controlled mutability in modern C#.
An instance member belongs to a particular object, while a static member belongs to the type itself.
- Instance methods can access the current object through this.
- Static methods have no instance receiver and can directly access only static members.
- Static state is shared across callers in the process, so mutation of it needs deliberate design.
Why interviewers ask this: The interviewer is checking whether you understand ownership of members and the shared nature of static state.
virtual allows derived classes to replace a method's polymorphic implementation, and override supplies that replacement.
- Calls through a base reference dispatch to the runtime object's override.
- new hides an inherited member based on the reference's compile-time type instead of participating in the same virtual slot.
- The compiler warns about accidental hiding so the choice should be explicit.
Why interviewers ask this: A strong answer distinguishes runtime polymorphic overriding from compile-time member hiding.
An abstract class cannot be instantiated directly and can define members that derived classes must implement.
- Abstract members have no implementation in the base class and require an override in a concrete derived class.
- The abstract class can also contain implemented methods, fields, constructors, and state.
- A concrete class must provide all remaining abstract behavior before instances can be created.
Why interviewers ask this: The interviewer is evaluating basic inheritance vocabulary and the purpose of incomplete base types.
Locked questions
- 21
What is List<T>, and when is it useful?
- 22
How does an array differ from List<T>?
- 23
What is Dictionary<TKey, TValue>?
- 24
What is IEnumerable<T>?
- 25
What does foreach do with a collection?
- 26
What is LINQ?
linq - 27
What is deferred execution in LINQ?
linq - 28
How do Where and Select differ in LINQ?
linq - 29
How do First, FirstOrDefault, Single, and SingleOrDefault differ?
- 30
Why is Any usually clearer than Count() > 0 in LINQ?
linq - 31
What are try, catch, and finally used for?
- 32
Why should code catch specific exception types instead of Exception by default?
error-handling - 33
What is the purpose of a finally block?
- 34
What is the difference between throw and throw ex inside a catch block?
- 35
When should you create a custom exception type?
error-handling - 36
What do async and await mean in C#?
async - 37
What is Task in .NET?
async - 38
Why should asynchronous methods usually return Task or Task<T> instead of void?
async - 39
How is a result obtained from Task<T>?
async - 40
How do exceptions behave in an async Task-returning method?
asyncerror-handling - 41
What is an interface in C#?
types - 42
How does an interface differ from an abstract class?
types - 43
What are generics in C#?
generics - 44
What are generic constraints used for?
generics - 45
What is a generic method?
generics - 46
What is a delegate in C#?
delegationdelegates - 47
What are Action, Func, and Predicate delegates?
delegationdelegates - 48
What is an event in C#?
delegates - 49
What does the .NET garbage collector do?
gc - 50
Why does the .NET GC use generations?
- 51
How would you count how many times each word appears in a list of strings?
- 52
How would you remove duplicate IDs from a sequence while preserving their first-seen order?
- 53
A user enters an age as text. How would you convert it without throwing on invalid input?
- 54
Nullable reference warnings show that customer.Address may be null. How would you fix the code?
fundamentalsnullable - 55
Code removes items from a List<T> inside foreach and throws at runtime. How would you fix it?
- 56
How would you make a dictionary of email addresses treat different letter cases as the same key?
- 57
How would you process support tickets in the same order they were received?
concurrency - 58
How would you validate that brackets in an expression are correctly nested?
validation - 59
ToDictionary throws because the source contains duplicate product codes. How would you handle the data?
- 60
A method receives a collection but only needs to enumerate it. What parameter type would you choose?
- 61
How would you use LINQ to return the names of active users who are at least 18?
linq - 62
How would you sort orders by newest date first and then by order number?
- 63
How would you calculate the total sales amount for each customer with LINQ?
linq - 64
You have customers and orders in memory. How would you produce each order with its customer name?
memory - 65
Each department contains a list of employees. How would you return one flat employee sequence?
- 66
First throws when no matching user exists. How would you change the lookup?
- 67
A LINQ query is created, the source list changes, and the later result unexpectedly changes too. How would you fix it?
querieslinq - 68
A method enumerates the same LINQ sequence several times and repeats expensive work. How would you improve it?
linq - 69
How would you check whether any overdue invoice exists without counting all matches?
- 70
An EF Core query loads every product before filtering by category. How would you fix it?
queriesorm - 71
How would you write an asynchronous method that loads a user and returns no value when the user is absent?
async - 72
A controller calls SaveAsync without await and returns success before the save finishes. How would you fix it?
async - 73
Code uses task.Result inside an async request path and sometimes hangs or blocks threads. What would you change?
asyncconcurrency - 74
Three independent API calls are awaited one after another. How would you reduce the total wait time?
asyncapi - 75
When should two async operations remain sequential instead of using Task.WhenAll?
async - 76
How would you propagate cancellation from an ASP.NET Core request to EF Core?
resilienceaspnetorm - 77
How would you add a two-second timeout to an async operation that already accepts cancellation?
resilienceasync - 78
One task passed to Task.WhenAll fails. How would you handle the combined operation?
async - 79
An asynchronously created stream must be disposed after use. How would you write the method?
async - 80
A service creates a new HttpClient for every request and starts failing under load. How would you fix it?
debugging - 81
Select returns IEnumerable<Task<Product>> when loading product details. How would you obtain the products?
async - 82
A catch block ignores every Exception and returns null. How would you improve it?
fundamentalserror-handling - 83
A catch block uses throw ex and the stack trace points to the catch line. How would you fix it?
debugging - 84
How would you guarantee that a file stream is closed when parsing throws an exception?
error-handling - 85
A repository throws SqlException directly to a controller. How would you prevent database details from leaking?
database - 86
How would you retry an operation only for a specific transient exception?
resilienceerror-handling - 87
A lookup commonly fails because user input is invalid. Should the method throw an exception?
error-handling - 88
Where would you log an exception so it is not written several times?
error-handling - 89
An ASP.NET Core endpoint receives invalid input. How would you avoid returning a generic 500 error?
genericsendpointsaspnet - 90
How would you make an order service testable when it currently creates its email sender internally?
- 91
How would you implement a payment service that can switch between card and bank-transfer behavior?
- 92
A class implements a large interface but throws NotSupportedException for half its methods. How would you improve it?
types - 93
How would you create a reusable result type that can contain either data or an error message?
- 94
How would you write a generic method that returns the first matching item or reports that none exists?
generics - 95
How would you implement a generic in-memory cache with string keys?
cachingmemorygenerics - 96
A method casts every object to Customer and crashes when another type appears. How would you fix it?
- 97
How would you deserialize different API response bodies with one reusable method?
api - 98
How would you constrain a generic method that compares entities by their integer ID?
generics - 99
How would you add a reusable IsNullOrEmpty check for IEnumerable<T>?
- 100
How would you test a service that depends on an interface-based product repository?
types