Module 1 · Foundations · Lesson 2 of 22
Core C# and CLR basics
If you copy a number and change the copy, does the original change? What if the variable holds a list instead? Start here before memorizing the terms.
Predict two assignments
Put this in Program.cs in a .NET console app. Pause before running it to predict the two lines of output.
int original = 7;
int copy = original;
copy = 9;
Console.WriteLine(original);
var names = new List<string> { "Asha" };
var alias = names;
alias.Add("Ravi");
Console.WriteLine(names.Count);intis a value type. The assignment copies the number into a separate variable. Assigning9tocopyleavesoriginalat7.List<string>is a class, which is a reference type. The assignment copies the reference, not the list. Both variables now refer to the same object. Adding a name throughaliasmakesnames.Countprint2.- The CLR is the part of .NET that runs managed code and provides services such as garbage collection. These examples tell you how assignment behaves; they do not tell you where any particular variable is stored in memory.
In the list example, what would names.Count be if alias were assigned a new empty list before alias.Add("Ravi")?
Show answer
Correct answer: A
Reassigning alias changes only which object alias refers to. It does not change the original list or the reference stored in names.
Hint: Separate replacing a reference from changing the object it points to.
Run dotnet run and compare your prediction. Then work through the reference examples below to connect assignment with casting, boxing and other interview topics.
Attempt before the reference answer
Copy an integer and copy a Person reference. Change the copied integer, mutate the shared Person, then reassign only the second reference. Predict both variables after each operation before reading the existing three-outcome example.
Trace to compare
| Operation | First variable | Second variable |
|---|---|---|
| b = a; b = 20 when a was 10 | a remains 10 | b becomes 20 |
| p2 = p1; mutate p2.Name | p1 sees the shared object’s new Name | p2 sees the same object’s new Name |
| p2 = a new Person | p1 still points to the original object | p2 points to a different object |
Decision check
After p2 = p1, assigning p2 to a new Person does what to p1?
Show answer
Correct answer: D
The assignment changes the reference stored in p2. It does not change p1, and it is separate from mutating an object that both variables reference.
Option A: The variables contain separate copies of the reference.
Option B: Reassignment does not copy fields into the old object.
Option C: The declared type does not change.
Hint: Draw variables and objects separately.
Reference questions
Before you start
Be comfortable reading a variable assignment, an if, a method call and a simple class. You do not need to memorize CLR internals first.
Your goal: Give a clear 30-second answer, predict a small example's output, then explain one limitation or trade-off. This lesson covers values and types (copying, casting, boxing and nullability), everyday choices about strings, initialization and numbers, and API design and runtime follow-ups.
Treat examples as independent snippets, not one combined program. Use .NET 8 / C# 12 or later for the examples. Some snippets illustrate a type or member declaration rather than a complete program; member declarations belong inside a suitable type. Raw strings and generic math need C# 11 or later; generic math also needs .NET 7 or later.
Question 1. What is the difference between casting, conversion, and parsing?
Conversion changes a value from one type to another. It can happen automatically or be requested explicitly.
Casting uses (TargetType) to request an explicit conversion.
Parsing reads text in an expected format and turns it into a typed value.
int count = 12;
long wider = count; // Conversion: int to long, automatically.
int whole = (int)12.7; // Cast: drops the fractional part, giving 12.
int parsed = int.Parse("12"); // Parse: reads the string "12" as the number 12.A cast is one way to convert. It doesn't read numeric text. For user input, use int.TryParse so you can check whether parsing worked.
Read more: Type conversions.
Question 2. What is object casting and pattern matching?
Object casting: A reference cast such as (string)value tells C# to use a reference as a particular type. You can then access string members without changing the object. If a non-null object isn't compatible with the type, the cast throws InvalidCastException.
Pattern matching with value is string text checks the type and gives you a typed variable if the check succeeds. Use it when you don't know what kind of object you have.
using System;
object value = "hello";
string cast = (string)value;
Console.WriteLine(cast.Length); // 5
value = 10;
if (value is string text)
Console.WriteLine(text.Length);
else
Console.WriteLine("Not a string"); // Not a stringThe first value refers to a string, so the cast works. After the assignment it holds a boxed int (an integer stored as an object), so the pattern doesn't match. Repeating (string)value at that point would throw.
Follow-up: A type pattern doesn't parse text, convert a boxed int to long, or match null. Where the conversion is permitted, as returns null if the runtime type is incompatible. Its target must be a reference type or a nullable value type.
Read more: Type tests and casts.
Question 3. What is boxing and unboxing?
Boxing copies a value, such as an int, into an object. For example, object box = score takes a copy of the int in score. Changing score later doesn't change the boxed copy. Boxing can also happen when you assign a value type to an interface it implements.
Unboxing takes that value back out. Here the box contains an int, so unbox it with (int)box. (long)box throws InvalidCastException because the box contains an int, not a long. If you want a long, unbox the int first, then convert it.
using System; int score = 42; object box = score; // Box a copy of 42 score = 99; Console.WriteLine(score); // 99 Console.WriteLine((int)box); // 42 Console.WriteLine((long)(int)box); // 42 as a long // Console.WriteLine((long)box); // InvalidCastException if uncommented
Why it matters: Repeated boxing can create extra objects for the garbage collector. Use List<int> for a list of integers: it stores them without boxing each one, unlike putting the same integers into a List<object>.
Read more: Boxing and unboxing.
Question 4. Value type vs reference type?
Interview answer (30 seconds): A value-type variable holds its value directly, so ordinary assignment copies the value. A reference-type variable holds a reference to an object, so assignment copies the reference, not the object. Two references can therefore share the same mutable object: changing that object is visible through both. Reassigning one reference changes only what that variable points to. The key distinction is what gets copied, not “stack versus heap.”
Examples: int, bool, struct and enum are value types. Classes, arrays and string are reference types. string is a reference type, but it is immutable; sharing a reference does not make an object mutable.
See the difference
These are logical snapshots, not a stack/heap memory map.
| Snapshot | Variables | Objects / values |
|---|---|---|
| Value copy | a = 10; b = a; b = 20 | a remains 10; b is 20 |
| Shared reference after mutation | p1 and p2 refer to one Person | Both observe Name = Updated |
| After reassigning p2 | p1 refers to the original; p2 refers to a new Person | Original Name = Updated; new Name = New |
One example, three outcomes
using System;
int a = 10;
int b = a;
b = 20;
Console.WriteLine($"{a}, {b}"); // 10, 20
var p1 = new Person { Name = "Raj" };
var p2 = p1;
p2.Name = "Updated";
Console.WriteLine($"{p1.Name}, {p2.Name}"); // Updated, Updated
p2 = new Person { Name = "New" };
Console.WriteLine($"{p1.Name}, {p2.Name}"); // Updated, New
class Person
{
public string Name { get; set; } = "";
}- Copy a value:
bgets its ownint; assigning20to it leavesaunchanged. - Copy a reference:
p1andp2identify onePerson; changing itsNameis visible through either variable. - Reassign a reference:
p2 = new Person { ... }selects a different object. It does not replace the object referenced byp1.
Avoid these interview traps
- “Value types live on the stack.” Not always. A value can be stored inside a heap object or array, and boxing creates a heap object containing a copy. Type semantics do not dictate one storage location.
- “Reference types are passed by reference.” Not by default. C# passes arguments by value, including a copy of an object reference. A method can mutate the shared object. Passing with
refalso lets it reassign the caller’s variable.
One nuance: copying a struct copies its fields, not an entire object graph. Reference-type fields can still refer to shared objects.
Remember: Assignment copies the variable’s contents: a value or a reference.
Read more: Microsoft’s value types and method parameters.
Question 5. Do value types inherit from object?
Interview answer: Yes. Struct types derive from System.ValueType, which derives from System.Object; enums derive through System.Enum. This type relationship does not mean every value is stored in a separate heap object.
using System; int count = 5; object boxed = count; Console.WriteLine(boxed.GetType() == typeof(int)); // True Console.WriteLine(typeof(int).BaseType == typeof(ValueType)); // True
Why: count is an int value; converting it to object boxes a copy. Inheritance describes the type system, while boxing describes a particular conversion.
Avoid the blanket claim: Converting an ordinary struct to an interface reference boxes it, but calling its interface implementation through a constrained generic type parameter need not. A ref struct cannot be boxed, even when it implements an interface in supported C# versions.
Read more: Common type system, constrained calls, and ref struct restrictions.
Question 6. Class vs struct: when should each be used?
Use a class when callers should work with the same object. A class is a reference type: assigning it to another variable copies the reference, not the object. For example, an order is still the same order when its status changes. A class is also the choice if you need to derive from a base class.
Use a struct for a small value that should copy on assignment, such as a quantity. A struct is a value type. Prefer keeping it immutable so callers replace the value rather than accidentally changing a copy.
using System;
var order = new Order();
var sameOrder = order;
sameOrder.Status = "Shipped";
Console.WriteLine(order.Status); // Shipped
var quantity = new Quantity(2);
var changed = quantity;
changed = new Quantity(3);
Console.WriteLine($"{quantity.Units}, {changed.Units}"); // 2, 3
class Order
{
public string Status { get; set; } = "Pending";
}
readonly record struct Quantity(int Units);Rule of thumb: Start with a class unless value-copy behavior helps model the problem. Don't choose a struct just to put it on the stack: storage depends on how the value is used, and large structs can be expensive to copy.
Read more: Classes and structure types.
Question 7. Are nullable types reference types?
Interview answer: Distinguish two features. int? is Nullable<int>, a value type representing an integer or no value. string? is a nullable reference annotation: it helps compiler null-state analysis but does not create a new runtime wrapper type.
using System;
int? age = null;
Console.WriteLine(age.HasValue); // False
Console.WriteLine(age ?? -1); // -1
age = 30;
if (age is int years)
Console.WriteLine(years); // 30Why: ?? supplies a fallback only when no value exists. Reading age.Value while it is null throws InvalidOperationException; a pattern can check and extract in one step.
Follow-up: Nullable<T> requires a non-nullable value type. Boxing a null int? produces a null reference; boxing a populated int? boxes its underlying int. Nullable reference annotations are warnings and analysis, not a runtime guarantee against null.
Read more: Nullable value types and nullable reference types.
Question 8. What is the difference between object and System.Object, string and System.String?
There is no type difference. object and string are C# keywords for the .NET types System.Object and System.String. Each pair is two names for the same type. The same goes for int and System.Int32, or long and System.Int64.
using System; string message = "hello"; System.String sameType = message; // No conversion needed Console.WriteLine(typeof(string) == typeof(System.String)); // True Console.WriteLine(typeof(object) == typeof(System.Object)); // True
typeof checks the type named in the code. Both comparisons are True because the compiler uses the same .NET type either way. This is a spelling choice, not a performance choice. Follow your codebase's style; the C# keywords are common in declarations.
Read more: C# built-in types.
Question 9. Why are strings immutable in C#?
Answer: A string is immutable: its text cannot change after the string is created. Methods like Replace, Substring, and ToUpperInvariant return a result instead of editing the original string. A string variable can still be assigned a different value.
string original = "draft";
string title = original;
title = title.Replace("draft", "ready");
Console.WriteLine(original); // draft
Console.WriteLine(title); // readyAt first, both variables refer to the same string. Replace returns "ready", and the assignment changes title only. If the operation doesn't change the text, it may return the existing string rather than allocate another one.
Why it matters: Code can share a string without worrying that another caller will edit it. A string used as a dictionary key cannot change its text after insertion. The runtime can also reuse an interned string instance because the text cannot change.
Question 10. string vs StringBuilder?
Interview answer: Use strings for ordinary immutable text and straightforward interpolation or concatenation. Consider StringBuilder when accumulating many pieces, especially in a loop. It is a mutable builder, not an automatically faster replacement for every string operation.
using System;
using System.Text;
var builder = new StringBuilder();
for (int i = 1; i <= 3; i++)
builder.Append(i).Append(';');
Console.WriteLine(builder.ToString()); // 1;2;3;Why: The builder accumulates text instead of repeatedly constructing an entire new growing string. ToString() produces the string result. If the pieces already form a collection, string.Join may express the intent more clearly.
Follow-up: Choose for readability first, then measure relevant workloads. A small interpolation is not evidence that you need a builder.
Read more: StringBuilder guidance.
Question 11. How should case-insensitive string comparison be done?
Interview answer: Make the comparison rule explicit. For nonlinguistic identifiers that are defined as case-insensitive, use StringComparison.OrdinalIgnoreCase. For linguistic text, select an appropriate culture-aware comparison. Case sensitivity is a domain rule, not something to switch off everywhere.
using System;
using System.Collections.Generic;
Console.WriteLine(string.Equals(
"READY", "ready", StringComparison.OrdinalIgnoreCase)); // True
var codes = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
codes.Add("READY");
Console.WriteLine(codes.Contains("ready")); // TrueWhy: The same comparer makes collection lookup consistent with the equality rule. Changing both strings to uppercase or lowercase adds unnecessary transformations and can accidentally introduce culture-dependent behavior.
Trap: Passwords and other case-sensitive tokens must not use a case-insensitive rule. Sorting natural-language names is not the same problem as matching a protocol code.
Read more: String comparison best practices.
Question 12. Is string.Empty faster than ""?
Answer: There is no meaningful speed difference in normal code. string.Empty and "" both represent a string of length zero. Use the spelling your team finds clearer; choose the check based on what counts as missing input.
For example, an empty name has no characters. A name containing three spaces isn't empty, but you might still want to reject it.
name | name == string.Empty (or name == "") | string.IsNullOrWhiteSpace(name) |
|---|---|---|
null | false | true |
"" | true | true |
" " (three spaces) | false | true |
"Raj" | false | false |
Use equality when only the empty string should count (not null). Use string.IsNullOrEmpty(name) if null or empty should count, and string.IsNullOrWhiteSpace(name) if whitespace-only text should count as well.
Question 13. What is a verbatim string literal?
Answer: A verbatim string starts with @. It does not treat backslash as an escape character, and it can span multiple lines. Double quotes inside it are escaped by doubling them.
string path1 = @"C:\temp\data.txt"; string path2 = "C:\\temp\\data.txt"; string sql = @" SELECT Id, Name FROM Users WHERE Name = @name"; string quote = @"He said, ""Hello"".";
Question 14. What are raw string literals?
Interview answer: Raw string literals, available from C# 11, use a matching delimiter of at least three double quotes. They let us write quotes and backslashes directly, which is useful for JSON and other structured text.
using System;
string json = """{"name":"Raj","active":true}""";
Console.WriteLine(json.Contains("\"name\"")); // TrueFollow-up: Use more delimiter quotes when the content contains a run of quotes that would otherwise close the literal. In a multiline raw string, the closing delimiter's indentation determines the indentation removed from the content. Raw strings change C# literal syntax; they do not validate JSON or make interpolated SQL safe. Continue using SQL parameters for data.
Read more: Raw string literals.
Question 15. const, readonly, and static readonly?
Interview answer: const is a compile-time constant. An instance readonly field can be assigned at declaration or inside its declaring type's instance constructor. A static readonly field can be assigned at declaration or inside that type's static constructor. These constructor assignments can occur more than once during initialization.
Type declaration example:
using System;
using System.Collections.Generic;
public sealed class RetryPolicy
{
public const int DefaultAttempts = 3;
public readonly int Attempts;
public static readonly TimeSpan Delay = TimeSpan.FromSeconds(2);
public readonly List<string> Reasons = new();
public RetryPolicy(int attempts) => Attempts = attempts;
}Trap: readonly protects the field's value, not the entire referenced object. policy.Reasons.Add("timeout") is allowed; replacing policy.Reasons after construction is not.
Versioning follow-up: A consuming assembly embeds a const value at compile time. Changing a library's public constant may require rebuilding its consumers. Use static readonly for a runtime-initialized value, not a const merely because the value rarely changes.
Read more: readonly fields and constants.
Question 16. Static field initializer vs static constructor?
Interview answer: Use a static field initializer for a simple expression and a static constructor for multi-step type initialization. An explicit static constructor also changes initialization timing semantics, so adding an empty one is not entirely neutral.
Type declaration example:
public sealed class Settings
{
public static readonly string AppName = "InterviewPrep";
public static readonly string DisplayName;
static Settings()
{
DisplayName = AppName + " / C#";
}
}Why: The field initializer runs before this type's static constructor, so DisplayName receives InterviewPrep / C#. An explicit static constructor prevents the type from receiving the BeforeFieldInit flag, which would otherwise allow more flexible initialization timing.
Trap: Keep initialization short and avoid blocking on tasks or locks. A failed static constructor is not automatically retried; later use can fail with TypeInitializationException. Do not use it as a recoverable network-configuration workflow.
Read more: Static constructors.
Question 17. What are default access modifiers in C#?
Interview answer: A namespace-level class or struct defaults to internal; a class or struct member defaults to private. Interface members are public by default, but modern interfaces can declare explicit access modifiers, including private members with implementations. Enum members are public.
Type declaration example:
class CustomerService // internal type
{
string _name = ""; // private field
void Save() { } // private method
CustomerService() { } // explicitly declared private constructor
}The constructor trap: For a non-static class with no declared instance constructor, the compiler supplies a parameterless constructor that is public, or protected for an abstract class. That does not make an internal class accessible outside its assembly. An explicitly written constructor with no access modifier, as above, is private.
Read more: Access modifiers and default interface member design.
Question 18. Why do we need namespaces?
Answer: Namespaces organize code and prevent name collisions. Two classes can have the same name if they live in different namespaces.
namespace Billing
{
public class Invoice { }
}
namespace Shipping
{
public class Invoice { }
}Interview tip: Namespaces are about logical organization; assemblies are about deployment/versioning.
Question 19. var vs dynamic?
Interview answer: var asks the compiler to infer a local variable's static type; it does not weaken type checking. dynamic defers binding of operations involving it until runtime, so code can compile and still fail when executed.
using System; var count = 10; // count = "ten"; // Compile-time error if uncommented dynamic value = "ten"; Console.WriteLine(value.ToUpperInvariant()); // TEN value = 10; // value.ToUpperInvariant(); // RuntimeBinderException if uncommented
Why: count remains an int. The first dynamic invocation finds a string method; the second would try to find that method on an int.
Follow-up: object is different: arbitrary member calls are rejected at compile time until you cast or pattern-match. Prefer known types for normal application code; use dynamic for a genuine dynamic API or interop requirement, not merely to avoid declaring a model.
Read more: Using dynamic.
Question 20. What are numeric literal suffixes?
Interview answer: A suffix is a letter (or pair of letters) after a number written in code. The compiler uses it to determine the literal’s type before var infers the variable’s type. For example, adding m makes 12.50 a decimal instead of a double.
using System; var price = 12.50m; var measurement = 12.50; var ratio = 0.5f; Console.WriteLine(price.GetType().Name); // Decimal Console.WriteLine(measurement.GetType().Name); // Double Console.WriteLine(ratio.GetType().Name); // Single (float)
For real literals, M selects decimal, F selects float, and D explicitly selects double (for example, 0D). For integer literals:
U(as in0U): first type that can represent the value, in the orderuint,ulong.L(as in0L): first type that can represent the value, in the orderlong,ulong. Prefer uppercaseLso it doesn’t look like1.UL(as in0UL):ulong.
For typical prices, use decimal to represent decimal amounts such as 12.50 exactly. Still decide when and how to round.
Read more: Real literals and Integer literals.
Question 21. decimal vs double vs float?
Interview answer: float and double use binary floating-point; decimal represents decimal fractions such as 0.1 exactly within its range and precision. Use decimal for typical financial amounts with explicit rounding rules; choose float or double for workloads that need their range, precision and performance characteristics.
using System; Console.WriteLine(0.1 + 0.2 == 0.3); // False Console.WriteLine(0.1m + 0.2m == 0.3m); // True Console.WriteLine(1m / 3m * 3m == 1m); // False
Why: Binary approximations affect the first equality. Decimal exactly represents the values in the second, but cannot exactly represent one third, so it is not unlimited-precision arithmetic.
Follow-up: For approximate measurements, choose an error tolerance appropriate to the scale and domain, not a universal magic epsilon. For money, define the currency, rounding stage and midpoint rule; the numeric type alone is not a complete financial policy.
Read more: Floating-point numeric types.
Question 22. What is banker rounding?
Interview answer: Banker's rounding means rounding an exact midpoint to the nearest even result at the chosen precision. Math.Round overloads without an explicit midpoint mode use MidpointRounding.ToEven. This does not mean every number is rounded to an even number.
using System; Console.WriteLine(Math.Round(2.5m)); // 2 Console.WriteLine(Math.Round(3.5m)); // 4 Console.WriteLine(Math.Round(3.1m)); // 3 Console.WriteLine(Math.Round(2.5m, MidpointRounding.AwayFromZero)); // 3
Why: Only the two exact .5 ties use the even-neighbor rule; 3.1 is simply nearer to 3. Decimal inputs keep these decimal midpoint examples exact.
Trap: AwayFromZero chooses away from zero at a midpoint; it does not round every noninteger away from zero. Document the business rule rather than assuming one rounding mode is universally correct.
Read more: Math.Round.
Question 23. What is nameof used for?
Interview answer: nameof gives you the name of a variable, type, or member as a string at compile time. It does not read the value stored in a variable.
using System; string name = "Raj"; Console.WriteLine(nameof(name)); // name Console.WriteLine(name); // Raj
Use it when another API needs an identifier as text. For example, in a method with a name parameter, new ArgumentException("A name is required.", nameof(name)) records the parameter name. If you rename the parameter using your editor’s rename feature, it updates the nameof reference, but a hard-coded string like "name" can stay stale. Some modern guard methods already capture the supplied argument expression, so you often don’t need to pass nameof explicitly.
Read more: nameof expression.
Question 24. What are expression-bodied members?
Interview answer: An expression-bodied member uses => when one expression is enough to describe what the member does. For a method that returns a value, the expression takes the place of the braces and return statement.
Suppose an order total is just the item price plus shipping. Both methods below calculate the same amount:
using System;
Console.WriteLine(Order.TotalWithBlock(20, 5)); // 25
Console.WriteLine(Order.TotalWithExpression(20, 5)); // 25
static class Order
{
public static int TotalWithBlock(int price, int shipping)
{
return price + shipping;
}
public static int TotalWithExpression(int price, int shipping) => price + shipping;
}Here => defines the body of a named method; it isn’t a lambda. Properties and constructors can also use expression bodies. Use a block when the logic needs several steps, such as checking inputs before calculating the total.
Read more: Expression body definitions.
Question 25. What is a tuple / ValueTuple?
Interview answer: C# tuple syntax groups values using System.ValueTuple value types. Tuples support names and deconstruction, but their fields are mutable. They suit small local results; use a named domain type when invariants or a durable public contract matter.
using System;
var (success, value) = TryReadCount("42");
Console.WriteLine($"{success}, {value}"); // True, 42
static (bool Success, int Value) TryReadCount(string input)
{
return int.TryParse(input, out int count)
? (true, count)
: (false, 0);
}Why: Deconstruction assigns the two returned values to local variables. On failure, the Boolean is false; do not mistake the fallback zero for a successful parse.
Follow-up: Tuple field names are not distinct runtime type identities. (int X, int Y) and (int Width, int Height) do not become separate domain types because their labels differ. System.Tuple<...> is a different, reference-type family.
Read more: Tuple types.
Question 26. What is an indexer?
Interview answer: An indexer lets you use brackets ([]) on an object of your own type. For example, statuses[0] can read the first status just like an array does. Reading calls the indexer’s get; assigning calls its set.
using System;
var statuses = new StatusList();
Console.WriteLine(statuses[0]); // draft
statuses[0] = "ready";
Console.WriteLine(statuses[0]); // ready
sealed class StatusList
{
private readonly string[] _items = { "draft", "queued" };
public string this[int index]
{
get => _items[index];
set => _items[index] = value;
}
}this[int index] declares the indexer. Unlike a normal C# property, an indexer takes an argument. This one uses an int because it wraps an array; a lookup type could accept a string key instead. This example initializes every slot, so the first read returns a status rather than null.
Read more: C# indexers.
Question 27. What is operator overloading?
Interview answer: Operator overloading lets a type define what an operator like + means for its values. Here, adding a price and a shipping charge gives a new Money value. Both amounts are assumed to be in the same currency; the example neither tracks currency nor converts it.
using System;
var total = new Money(12.50m) + new Money(2.00m);
Console.WriteLine(total.Amount == 14.50m); // True
public readonly record struct Money(decimal Amount)
{
public static Money operator +(Money left, Money right) =>
new(left.Amount + right.Amount);
}When both operands are Money, C# calls the static binary + overload. It adds their decimal amounts and returns a new Money value. Only overload an operator when its meaning is what callers would expect; for currency conversion, use a named method instead.
Read more: Operator overloading.
Question 28. Why can some operators not be applied to generic types?
Interview answer: A generic method can use only operations guaranteed by its type parameter's constraints. An unconstrained T does not promise a + operator. C# 11 and .NET 7 introduced the language and library support used by generic math to express such requirements.
using System;
using System.Numerics;
Console.WriteLine(Add(3, 4)); // 7
static T Add<T>(T a, T b) where T : IAdditionOperators<T, T, T>
=> a + b;Why: The constraint promises the required static addition operator. It does not promise a particular numeric meaning or overflow policy for every possible implementing type.
Follow-up: Prefer the narrow capability you need. An addition-only helper need not require every operation exposed by INumber<T>. On older targets, use an explicit operation/delegate or a type-specific implementation instead of assuming where T : struct guarantees arithmetic.
Read more: Generic math.
Question 29. What causes OutOfMemoryException?
Interview answer: .NET can throw OutOfMemoryException when it can’t make an allocation. That can happen even when the machine still has free RAM, for example if the process has a 32-bit address-space limit or there’s no large enough contiguous block of memory. Oversized collections, pinned objects that contribute to fragmentation, and unmanaged leaks can also put pressure on memory.
Suppose you only need to count error lines in a log. You don’t need to keep every line:
using System;
using System.IO;
using var reader = new StringReader("OK\nERROR\nOK");
int errors = 0;
while (reader.ReadLine() is string line)
{
if (line == "ERROR") errors++;
}
Console.WriteLine(errors); // 1The demo string is already in memory; the loop shows how to process one line at a time without accumulating them. For a real file, use File.OpenText(path) in the using declaration instead. It reads through a buffer rather than loading the whole file up front. A single very long line, or storing every result, can still use substantial memory.
Interview follow-up: An operating system can also terminate a process under memory pressure, for example when a Linux container exceeds its memory limit. That’s different from .NET throwing a managed exception you can catch.
Read more: OutOfMemoryException and File.OpenText.
Question 30. What is the stack and heap in .NET?
Interview answer: A thread's stack supports active method calls and their execution state. The managed heap is storage managed by the garbage collector. Do not derive a variable's physical location solely from whether its type is a value type or a reference type: fields, captured variables and runtime optimizations matter.
using System;
int[] counts = { 10, 20 };
int copy = counts[0];
copy = 99;
Console.WriteLine(counts[0]); // 10
Console.WriteLine(copy); // 99Why: Array elements are stored in the array, including value-type elements. Reading the first int copies its value. This example establishes copying behavior; it does not measure whether the runtime keeps copy in a stack slot or a register.
Follow-up: GC tracks reachability, not simply whether a source-level scope has ended. Do not use a stack/heap slogan to explain deterministic cleanup: release disposable resources with using/Dispose, rather than waiting for collection.
Read more: GC fundamentals and value types.
Recall check: explain before looking back
Close the examples and answer these aloud. Aim for the reason, not just the output.
- You box
int n = 7, then setn = 9. What does unboxing return, and can you directly unbox it aslong? - Can
int?be null without being a reference type? How isstring?different? - A
readonlyfield references aList<string>. Can you add an item after construction? Can you replace the list? - Should a case-insensitive protocol-code dictionary use the current culture or an ordinal comparer?
- Does
decimalremove the need for financial rounding rules? Explain why.
Check your reasoning:
7: boxing copied the earlier value. Unbox asint, then convert tolong(Q3).- Yes:
int?is a nullable value type;string?is a reference-type annotation for null analysis (Q7). - Adding is allowed; assigning a different list to that field after construction is not. Readonly is not deep immutability (Q15).
- Use an explicitly chosen ordinal case-insensitive comparer for that nonlinguistic rule (Q11).
- No. Finite precision and the business's rounding stage/mode still matter (Q21–22).
Ready to continue? You should be able to explain the five answers without copying their wording and give a new example. If you missed one, revisit its question before taking the Foundations practice test. Then continue to OOP, delegates, generics, and reflection. These recall prompts are a study aid, not a timed mock or a scored assessment.
Practice
TechInterviewNotes Editorial Team · Updated 28 Oct 2026 ·