Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close
    Lesson2 / 10

    Equality, copying, nullability, and safe APIs

    C# lets you compare values, check whether two references point to the same object, and make copies. Learn to trace copies, handle nulls and report expected failures clearly.

    Start here: Zero is a value, not a failure flag

    Parsing means converting text into a value of a chosen type. Here, int.TryParse tries to turn text into an integer. It returns a Boolean, which is either true or false, and uses the out parameter to put a number in count.

    Before running the example, predict the Boolean and the number for each input.

    C#Runs
    foreach (string text in new[] { "0", "missing" })
    {
        bool parsed = int.TryParse(text, out int count);
        Console.WriteLine($"{parsed}:{count}");
    }
    Output
    True:0
    False:0

    The loop handles one input at a time. For "0", conversion succeeds, so parsed is true and count is 0. Console.WriteLine therefore prints True:0.

    For "missing", conversion fails. TryParse returns false and sets count to 0, producing False:0. Looking only at count would make these different outcomes look the same.

    Check parsed before using count. Then apply any separate business rule, such as whether an order quantity may be zero. The linked scored mock reviews these C# fundamentals and related topics.

    In an interview, say: “TryParse reports conversion success through its Boolean return value. Zero can be a valid parsed value, so I check the Boolean before validating the number.”

    Which check tells you that the input actually parsed?

    A count == 0
    B count != 0
    C The Boolean returned by TryParse
    D Whether there is an out variable at all
    Show answer

    Correct answer: C

    The Boolean distinguishes a successful zero from an unsuccessful conversion. Domain validation is a separate decision.

    Microsoft documentation

    Trace the copy before naming it deep

    An Order record holds a mutable List<OrderLine>. A with expression changes the status, then code adds a line through the copy. Predict the original list count. Next decide whether a new List<OrderLine> would also copy mutable OrderLine objects.

    Try first: write a prediction and the boundary that could invalidate it. The numbered questions below are reference answers, not a new scored exam. Use them to check a specific uncertainty after attempting the case.

    Hint: Follow outer-object identity, collection identity and element identity separately. Q19 uses immutable strings; do not silently carry that assumption to mutable elements.

    Reference answers

    Question 17. What is IEquatable<T> and why is it useful?

    Answer: IEquatable<T> defines strongly typed Equals(T). Generic equality infrastructure such as EqualityComparer<T>.Default can use it, so struct comparisons can avoid the boxing required by an object-based call. It is not a promise that every use avoids boxing: assigning a struct to an interface or passing it as object can still box it. It defines equality, not ordering.

    Example: This key uses case-sensitive, ordinal string equality. The nullable property deliberately accommodates default(ProductCode).

    This is a type definition to copy into a project. It does not include a console entry point that calls it.

    C#
    #nullable enable
    using System;
    using System.Collections.Generic;
    
    public readonly struct ProductCode : IEquatable<ProductCode>
    {
        public ProductCode(string value) => Value = value;
        public string? Value { get; }
        public bool Equals(ProductCode other) => Value == other.Value;
        public override bool Equals(object? obj) => obj is ProductCode other && Equals(other);
        public override int GetHashCode() =>
            Value is null ? 0 : StringComparer.Ordinal.GetHashCode(Value);
        public static bool operator ==(ProductCode left, ProductCode right) => left.Equals(right);
        public static bool operator !=(ProductCode left, ProductCode right) => !left.Equals(right);
    }

    new HashSet<ProductCode> { new("A1"), new("A1") }.Count is 1 (target-typed new requires C# 9+). Equal keys must have equal hash codes; unequal keys may collide. Keep equality-relevant state stable while a key is in a hash-based collection.

    If you implement IEquatable<T>, still override object.Equals and GetHashCode consistently. Implementing the interface alone does not define ==.

    Question 18. ReferenceEquals vs Equals: what is the difference?

    Answer: object.ReferenceEquals(a, b) tests identity: the same object instance, or both references null. It cannot be overridden. Equals tests the equality defined by the selected method: ordinary classes inherit reference equality unless they override it, while strings and records provide value-based equality. object.Equals(a, b) is null-safe; calling a.Equals(b) throws if a is null.

    Example: Construct separate strings rather than relying on literals, which can be interned.

    C#Runs
    using System;
    
    string a = new string(new[] { 'x' });
    string b = new string(new[] { 'x' });
    Console.WriteLine(object.ReferenceEquals(a, b)); // False
    Console.WriteLine(object.Equals(a, b));          // True
    
    int n = 42;
    Console.WriteLine(object.ReferenceEquals(n, n)); // False: two separate boxes
    object boxed = n;
    Console.WriteLine(object.ReferenceEquals(boxed, boxed)); // True
    Output
    False
    True
    False
    True

    Use ReferenceEquals only when identity matters, such as detecting object reuse or sentinel objects. It is not a value comparison for structs, and == is a separate, overloadable operator.

    Question 19. What is shallow copy vs deep copy?

    Answer: A reference tells the program which object to use. A shallow copy creates a new outer object and copies its stored values, including any references to other objects. Those nested objects remain shared.

    A deep copy also copies the mutable objects that must be independent. Mutable means that an object can change after it is created. Which objects need copying depends on the independence your application promises. Assigning a class reference to another variable creates no new object at all. Both variables refer to the same outer object.

    Example: Record classes and with require C# 9+. The compiler-generated record copy is shallow. Here, each Order has an ID and a reference to an Items list. Predict which list counts change when "Pen" is added.

    C#Runs
    using System;
    using System.Collections.Generic;
    
    var original = new Order(1, new List<string> { "Book" });
    var shallow = original with { Id = 2 };
    var independent = original with { Id = 3, Items = new List<string>(original.Items) };
    
    shallow.Items.Add("Pen");
    Console.WriteLine(original.Items.Count);    // 2
    Console.WriteLine(independent.Items.Count); // 1
    Console.WriteLine(object.ReferenceEquals(original, shallow)); // False
    Console.WriteLine(object.ReferenceEquals(original.Items, shallow.Items)); // True
    
    public sealed record Order(int Id, List<string> Items);
    Output
    2
    1
    False
    True

    Read the statements in order.

    1. original starts with a list containing "Book".
    2. original with { Id = 2 } creates a second record, shallow. Its ID changes, but its Items reference still points to the original list.
    3. new List<string>(original.Items) creates a separate list for independent. This happens before "Pen" is added, so the new list contains only "Book".
    4. shallow.Items.Add("Pen") changes the shared list. original.Items.Count is now 2, while independent.Items.Count remains 1.

    The final two lines ask about object identity, meaning whether two references identify the same object. The records original and shallow are different objects, so the first check prints False. Their Items properties identify the same list, so the second check prints True.

    flowchart TD
        original["original"] --> shared["List 1: Book, Pen"]
        shallow["shallow"] --> shared
        shared ~~~ independent["independent"]
        independent --> separate["List 2: Book"]

    The arrows follow each record's Items reference after the add, showing two records sharing one list and the third using its own list.

    Copying this list is sufficient to isolate its mutable state because its elements are immutable strings. A list of mutable OrderLine objects would still share those elements unless they were copied too. A general deep-copy strategy must decide how to handle cycles, shared references, and resources such as streams; serialization is not automatically a correct cloning contract.

    For immutable nested values, shallow copy is usually fine. For mutable nested values, be explicit.

    In an interview, say: “A shallow copy gives me a new outer object while nested objects can remain shared. I copy each mutable object that must change independently, and decide how shared references and cycles should behave.”

    Question 20. What are checked and unchecked numeric contexts?

    Answer: For built-in integral arithmetic such as addition, checked reports overflow with OverflowException; unchecked discards excess bits, producing wraparound. Overflow in a constant expression is a compile-time error by default, unless explicitly unchecked. Nonconstant expressions default to unchecked unless the compiler's CheckForOverflowUnderflow option changes that default.

    Example: Catching the checked overflow allows the unchecked example to run afterward.

    C#Runs
    using System;
    
    int x = int.MaxValue;
    try
    {
        Console.WriteLine(checked(x + 1));
    }
    catch (OverflowException)
    {
        Console.WriteLine("Overflow");
    }
    Console.WriteLine(unchecked(x + 1)); // -2147483648
    // int invalid = int.MaxValue + 1;  // compile-time error
    Output
    Overflow
    -2147483648

    The context is lexical: a checked block around a method call does not change arithmetic inside that method. It also affects relevant numeric conversions. It is not a universal numeric safety switch: decimal arithmetic overflow throws even in unchecked, while floating-point arithmetic does not gain overflow exceptions from checked. Division by zero is not made safe by unchecked.

    Use checked when integral overflow must be detected, and test boundaries. It does not replace range validation or a suitable numeric type.

    Question 21. What are nullable analysis attributes such as MemberNotNull?

    Answer: These attributes describe null-state contracts to the compiler. MemberNotNull promises that named members are non-null when the annotated method returns normally, not that the attribute itself initializes them. NotNullWhen(true) describes a parameter's state after a successful Boolean result; NotNullIfNotNull relates an output's state to an input's. Nullable analysis requires a nullable-enabled context (C# 8+); MemberNotNull support arrived with C# 9/.NET 5.

    Example: The loader may return null, so the method throws if it cannot establish a non-null value.

    This is a class fragment to copy into a project. A calling program must create ConnectionSettings and call GetConfiguredLength. The example also reads the APP_CONNECTION environment variable. It has no console entry point of its own.

    C#
    #nullable enable
    using System;
    using System.Diagnostics.CodeAnalysis;
    
    public sealed class ConnectionSettings
    {
        private string? _connectionString;
    
        [MemberNotNull(nameof(_connectionString))]
        private void EnsureConfigured()
        {
            _connectionString ??= Environment.GetEnvironmentVariable("APP_CONNECTION")
                ?? throw new InvalidOperationException("Missing connection configuration.");
        }
    
        public int GetConfiguredLength()
        {
            EnsureConfigured();
            return _connectionString.Length;
        }
    }

    If the environment variable is absent, the call throws. If it is "abc", the method returns 3. Non-null does not mean nonempty or a valid connection string; those are separate checks. The example does not claim thread safety.

    These attributes do not perform runtime validation by themselves; they improve compile-time analysis. Write code that actually fulfills the contract rather than hiding warnings with !.

    Question 22. What is the difference between a guard clause and validation?

    Answer: A guard clause is an early-exit control-flow pattern; validation is checking whether data satisfies rules. They overlap, rather than being opposites. API guards often throw standard argument exceptions for violated preconditions. Expected invalid user input is usually better represented as validation errors that a caller can display or map to a response.

    Example: C# 9+ and .NET 6+ (ThrowIfNull). This deliberately separates a null precondition from a normal validation result; it does not create an order.

    C#Runs
    #nullable enable
    using System;
    
    static string? ValidateOrder(CreateOrderRequest request)
    {
        ArgumentNullException.ThrowIfNull(request);
        if (request.Quantity <= 0)
            return "Quantity must be positive.";
        return null; // no validation error
    }
    
    Console.WriteLine(ValidateOrder(new CreateOrderRequest(0))); // Quantity must be positive.
    Console.WriteLine(ValidateOrder(new CreateOrderRequest(2)) is null); // True
    
    public sealed record CreateOrderRequest(int Quantity);
    Output
    Quantity must be positive.
    True

    A null argument throws before the quantity check. Returning a single error is enough here; larger forms may need multiple field-specific errors. In an ASP.NET Core controller with [ApiController], invalid model state normally triggers an automatic HTTP 400 response. An arbitrary ValidationException or returned error string is not automatically translated into that response; application/framework integration must handle it.

    Decide the error contract at the API boundary. “Fail fast” does not mean exposing stack traces or turning every invalid user input into a server error.

    Question 23. What are discriminated unions, and how do developers approximate them in C#?

    Answer: A discriminated union represents exactly one of a defined set of cases, each potentially carrying different data. In C# 14 and earlier, developers approximate this with records and inheritance, dedicated result types, or libraries. Unlike a closed union, an ordinary public class hierarchy does not give the compiler a complete set of possible subclasses for exhaustive matching.

    Example: This C# 9+ record hierarchy models two payment outcomes. The fallback remains necessary for null or an unrecognized subtype; it is not proof that the compiler checked every domain case.

    C#Runs
    using System;
    
    static string Describe(PaymentResult result) => result switch
    {
        PaymentAccepted ok => $"Accepted: {ok.TransactionId}",
        PaymentDeclined bad => $"Declined: {bad.Reason}",
        null => throw new ArgumentNullException(nameof(result)),
        _ => throw new InvalidOperationException("Unknown payment result.")
    };
    
    Console.WriteLine(Describe(new PaymentAccepted("tx-1"))); // Accepted: tx-1
    
    public abstract record PaymentResult;
    public sealed record PaymentAccepted(string TransactionId) : PaymentResult;
    public sealed record PaymentDeclined(string Reason) : PaymentResult;
    Output
    Accepted: tx-1

    This pattern is useful when a method has multiple valid outcomes and exceptions would be misleading. Explain both the case model and the limits of compiler exhaustiveness for the version you use.

    Question 24. What is a Result type and when is it better than exceptions?

    Answer: A Result type makes expected success or failure explicit in a method's return value. It is useful for outcomes such as a declined payment or rejected input that callers routinely handle. Exceptions still suit contract violations and failures the method cannot usefully handle. This is an API design choice, not a rule that every predictable failure must stop using exceptions; .NET also uses patterns such as TryParse.

    Example: A small C# 9+ case-based result avoids a public (Success, Value, Error) constructor that could create contradictory combinations. Each case exposes only its own payload.

    C#Runs
    #nullable enable
    using System;
    
    static Result<int> ParseQuantity(string text) =>
        int.TryParse(text, out int value) && value > 0
            ? new Result<int>.Ok(value)
            : new Result<int>.Fail("Enter a positive integer.");
    
    string message = ParseQuantity("abc") switch
    {
        Result<int>.Ok ok => $"Quantity: {ok.Value}",
        Result<int>.Fail failure => failure.Error,
        _ => throw new InvalidOperationException("Unexpected result.")
    };
    Console.WriteLine(message); // Enter a positive integer.
    
    public abstract record Result<T>
    {
        private Result() { }
        public sealed record Ok(T Value) : Result<T>;
        public sealed record Fail(string Error) : Result<T>;
    }
    Output
    Enter a positive integer.

    This is an illustrative domain type, not a built-in .NET Result<T> contract. With T = int, success carries an actual int, not a nullable placeholder for failure. Nullable annotations alone do not enforce runtime non-null payloads: add constructor/factory checks if your API must reject null values or empty errors. The private base constructor limits ordinary direct derivation, but this record pattern is not compiler-proven exhaustive matching.

    Do not replace all exceptions with Result. Use it where failure is part of the normal domain flow, and require callers to handle the outcome rather than ignoring it. Avoid blanket exception catches that turn programming bugs or cancellation into ordinary business failures.

    Compare your review comment

    A with expression copies the list reference, so the add is visible through both records. A new list separates membership, but keeps the same element references. Copy mutable lines deliberately when the required contract is a deep, independent graph.

    Check the primary contract: Record copy behavior.

    Check the decision

    An Order record holds a List<OrderLine> containing one line. Code creates a with-copy and adds a second line through the copy; no other mutation occurs. What is established?

    A Each record has its own list with one line because records are values.
    B Only the copy sees two lines because with clones collection fields.
    C Both see two lines, and every OrderLine was independently cloned.
    D Both see two lines; the outer record was copied but list membership is shared.
    Show answer

    Correct answer: D

    The record copy is shallow: a reference field still points at the same list. This establishes shared membership, not a deep element-copy guarantee.

    Hint: Follow outer-object identity, collection identity and element identity separately. Q19 uses immutable strings; do not silently carry that assumption to mutable elements.

    Practice

    Practice test: Mock Interview: C# Core Language (Mid-Level)25 questions · 35 minutes · 1 mark each, no negative marking
    Take the test
    Sign in to mark lessons done and keep your place in the course.Sign in

    TechInterviewNotes Editorial Team · Updated 24 Nov 2026 ·