Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close
    Lesson1 / 10

    Module 1 · Modern C#, Async and ASP.NET Core · Lesson 1 of 10

    Modern C# language features

    Start here: The target type gives brackets meaning

    A collection expression uses square brackets to build a collection from values. The surrounding code tells C# what kind of collection to build. That type is called the target type. In int[] morning = [2, 4];, the target type is int[], an array of integers.

    C#Runs
    int[] morning = [2, 4];
    int[] all = [..morning, 7];
    Console.WriteLine(string.Join(", ", all));
    Output
    2, 4, 7
    1. int[] morning = [2, 4]; creates the first array.
    2. int[] all = [..morning, 7]; creates a second array. The spread element ..morning copies the values from morning in order. The final element is 7. The original array still holds 2 and 4.
    3. string.Join(", ", all) puts a comma and space between the values. Console.WriteLine prints that text.
    flowchart TD
        morning["morning holds 2, 4"] -->|"Copy both values"| all["all holds 2, 4, 7"]
        seven["7"] -->|"Add last"| all

    The arrows show where each value in the new array comes from.

    If you replace the second int[] with var and leave the right side unchanged, what happens?

    A It infers int[] automatically
    B The expression has no target type and does not compile
    C It infers List<int>
    D It modifies morning instead
    Show answer

    Correct answer: B

    A collection expression needs a target type; var does not supply one on its own.

    Microsoft documentation

    Diagnose the language boundary

    Examples use C# 14 and .NET 10.

    A teammate wants to use square brackets to collect invoice totals and the Average<T> helper to compute their average. Before reading the answers, write two comments you would leave in the code review.

    1. What type should the invoice collection have? Point to where the code would give the bracket expression that type.
    2. Predict what Average<int>(3, 4) returns. Then predict the result of Average<decimal>(3m, 4m). Which kind of division does each call use?

    Use Questions 1 and 2 to check how C# builds the collection. Use Question 13 to trace how the helper adds and divides. Choose the money type and rounding rules that the invoice calculation requires.

    Reference answers

    Question 1. What are collection expressions in C#?

    Answer: Collection expressions (C# 12) use square brackets to create arrays, spans, lists, and other collection-like targets with one compact syntax. They are not LINQ queries; the elements are evaluated and a concrete collection is created for the target type.

    Example:

    C#
    int[] ids = [1, 2, 3];
    List<string> names = ["Raj", "Anita"];
    ReadOnlySpan<char> vowels = ['a', 'e', 'i', 'o', 'u'];

    Good answer: mention that [] is target-typed. var ids = [1, 2, 3]; has no target type and is invalid; use int[] ids = .... Do not assume the syntax always allocates an array on the heap: storage depends on the target and compiler lowering.

    Reference: Microsoft documentation.

    Question 2. What is the spread element in a collection expression?

    Answer: The spread element copies items from another collection into the new collection expression. It is useful for combining small sequences without manual AddRange calls.

    Example:

    C#
    int[] first = [1, 2];
    int[] second = [3, 4];
    int[] all = [0, ..first, ..second, 5]; // 0,1,2,3,4,5

    Do not confuse spread with lazy concatenation. The target collection is still created.

    Question 3. What is target-typed new?

    Answer: Target-typed new (C# 9) lets the compiler infer the type from the left side or parameter type. It reduces repetition, but overuse can make code less readable when the target type is far away.

    Example:

    C#
    Dictionary<int, string> cache = new();
    Order order = new(id: 10, total: 499.99m);
    CreateCustomer(new("Raj", "Pune")); // Customer inferred from parameter
    
    static void CreateCustomer(Customer customer) => Console.WriteLine(customer.Name);
    public record Customer(string Name, string City);
    public record Order(int id, decimal total);

    Use it where the target type is obvious. Avoid it in complex expressions where the reader must hunt for the type.

    Reference: Microsoft documentation.

    Question 4. What is a with-expression?

    Answer: A with-expression copies a record class (C# 9), struct/record struct, or anonymous type (C# 10), then assigns selected accessible members on the copy. It is commonly used for immutable models and request/response DTOs.

    Example:

    C#
    var draft = new Invoice(1, 1000m, "Draft");
    var approved = draft with { Status = "Approved" };
    
    public record Invoice(int Id, decimal Total, string Status);

    Mention non-destructive mutation: here draft.Status remains "Draft" and approved.Status is "Approved". The default record-class copy is shallow, as is a struct value copy: reference-valued members still refer to the same objects. Changing a shared list through the copy can affect what the original sees; with is not a deep-clone guarantee.

    Reference: Microsoft documentation.

    Question 5. What are extension blocks in C# 14?

    Answer: Extension blocks (C# 14) are syntax for grouping extension members for a type. They can define extension methods, extension properties, and static extension members. The older this-parameter extension method syntax still works.

    Example:

    C#
    bool missing = " ".IsBlank;
    
    public static class StringExtensions
    {
        extension(string value)
        {
            public bool IsBlank => string.IsNullOrWhiteSpace(value);
        }
    }

    Declare the block in a top-level, nongeneric static class and import its namespace where needed. missing is true. Extension lookup is compile-time; applicable real instance members win. Extensions do not grant access to the receiver type’s private members or add stored instance state.

    Reference: Microsoft documentation.

    Question 6. What is the C# field keyword in properties?

    Answer: The field contextual keyword (C# 14) lets a property accessor refer to the compiler-generated backing field without manually declaring a private field. It is useful for validation in auto-property-like code.

    Example:

    C#
    public string Name
    {
        get;
        set => field = string.IsNullOrWhiteSpace(value)
            ? throw new ArgumentException("Name is required")
            : value;
    } = "Unknown";

    Useful correction: field is contextual. If you already have a member named field, use @field when you mean that member.

    Behavior: A later assignment of " " throws before updating the backing field. The initializer sets the backing field directly, so it does not execute the setter’s validation. Choose a valid initializer; do not rely on the setter to validate it.

    Reference: Microsoft documentation.

    Question 7. What is a file-local type?

    Answer: A file-local type (C# 11) is visible only inside the source file where it is declared. It is useful for source generators or helper types that should not leak into the rest of the assembly.

    Example:

    C#
    file sealed class CsvToken
    {
        public required string Value { get; init; }
    }

    This is different from internal. internal is visible across the assembly; file is limited to one source file.

    Boundary: Declare it at namespace level, not as a nested type. It cannot be exposed as a field, parameter, or return type of a non-file-local type. required in this example is also C# 11; callers in this file must initialize Value. File locality is a source-name boundary, not a secret-data protection mechanism.

    Reference: Microsoft documentation.

    Question 8. What are partial classes and partial methods?

    Answer: partial lets a type or member be split across files and combined at compile time. It is common in generated code, UI designer code, and source-generator scenarios.

    Example:

    C#
    // Customer.g.cs - generated
    public partial class Customer
    {
        public Customer() => OnCreated();
        partial void OnCreated();
    }
    
    // Customer.cs - handwritten
    public partial class Customer
    {
        partial void OnCreated() => Console.WriteLine("created");
    }

    Keep business logic in handwritten files. Do not edit generated files unless the tool expects it.

    Follow-up: Constructing new Customer() invokes the hook and prints created. For this partial void declaration with no explicit accessibility and no out parameters, the implementation is optional; without it, the compiler removes the method and calls, including argument evaluation. Since C# 9, partial methods can have explicit accessibility or non-void returns, but those forms require an implementation. Keep matching declarations in the same type/assembly; partial is not runtime inheritance.

    Reference: Microsoft documentation.

    Question 9. What is explicit interface implementation?

    Answer: Explicit interface implementation implements an interface member so it is accessible only through the interface reference. It avoids public API pollution and resolves member-name conflicts.

    Example:

    C#
    IDisposable disposable = new Report();
    disposable.Dispose();
    
    public sealed class Report : IDisposable
    {
        void IDisposable.Dispose()
        {
            Console.WriteLine("Disposed through IDisposable");
        }
    }

    Use it when a member is part of a contract but should not be a normal public method on the class.

    Question 10. What is using static?

    Answer: using static imports static members of a type so they can be called without qualifying the type name. It is common for Math, assertion APIs, or test helper methods.

    Example:

    C#
    using static System.Math;
    double x1 = 0, y1 = 0, x2 = 3, y2 = 4;
    double distance = Sqrt(Pow(x2 - x1, 2) + Pow(y2 - y1, 2));

    Use sparingly. Too many using static imports can hide where methods come from.

    Result: distance is 5. This C# 6 directive changes name lookup, not resource disposal; it is unrelated to a using statement that disposes an object.

    Reference: Microsoft documentation.

    Question 11. What are CallerMemberName and CallerArgumentExpression used for?

    Answer: Caller info attributes substitute source information into omitted optional arguments at compile time, without stack inspection. CallerMemberName arrived in C# 5; CallerArgumentExpression in C# 10 (.NET 6). CallerMemberName is useful for logging and property change notification. CallerArgumentExpression is useful for guard clauses that report the failed expression.

    Example:

    C#
    using System.Runtime.CompilerServices;
    
    string? customer = null;
    NotNull(customer); // throws; ParamName is "customer"
    
    static void NotNull<T>(T? value,
        [CallerArgumentExpression("value")] string? expression = null)
        where T : class
    {
        if (value is null) throw new ArgumentNullException(expression);
    }

    An explicitly supplied optional argument overrides the compiler-provided text, so caller information is useful diagnostics, not trustworthy identity. In real guard code, ArgumentNullException.ThrowIfNull is often sufficient; the custom method here demonstrates the mechanism.

    Reference: Microsoft documentation.

    Question 12. What are static abstract members in interfaces?

    Answer: Static abstract interface members (C# 11) let an interface require static members such as operators or factory methods. They enable generic algorithms over numeric-like types.

    Example:

    C#
    static T Sum<T>(T a, T b) where T : IAddable<T> => a + b;
    
    public interface IAddable<TSelf>
        where TSelf : IAddable<TSelf>
    {
        static abstract TSelf operator +(TSelf left, TSelf right);
    }

    This is the language foundation behind many generic math APIs.

    Follow-up: The operator is available because T is constrained to IAddable<T>; an implementing type must supply a matching public static + operator (or an explicit implementation). Static abstract members are accessed through constrained type parameters, not by calling an abstract operator on the interface itself. This example defines the generic algorithm/contract; it does not supply a concrete IAddable<T> implementation.

    Reference: Microsoft documentation.

    Question 13. What is generic math in .NET?

    Answer: Generic math (.NET 7 with C# 11) lets you write numeric algorithms once and use them for int, decimal, double, and custom numeric types that implement the required numeric interfaces.

    Example:

    C#
    using System.Numerics;
    
    Console.WriteLine(Average(3, 4));     // 3: integer division
    Console.WriteLine(Average(3m, 4m));   // 3.5: decimal division
    
    static T Average<T>(T a, T b) where T : INumber<T>
    {
        return (a + b) / T.CreateChecked(2);
    }

    The constraint supplies operations, not identical numeric behavior. Integer division truncates; (a + b) can overflow before division. T.CreateChecked(2) checks that conversion only, not the addition. For a production average, choose the required result type and overflow policy explicitly; this small example illustrates generic operators, not an overflow-safe statistics routine.

    Reference: Microsoft documentation.

    Question 14. What do unmanaged, notnull, and default generic constraints mean?

    Answer: unmanaged (C# 7.3) restricts T to non-nullable value types with no managed references in their fields. notnull (C# 8) requests non-nullable type arguments; violations produce warnings in a nullable-enabled context, not a runtime null check. default (C# 9) disambiguates an override or explicit interface implementation whose inherited type parameter has neither a class nor a struct constraint. It is not a general-purpose constraint for new generic methods.

    Example:

    C#
    static int SizeOfValue<T>() where T : unmanaged
    {
        return System.Runtime.CompilerServices.Unsafe.SizeOf<T>();
    }
    
    static Dictionary<TKey, string> Create<TKey>() where TKey : notnull
        => new();

    Constraints are about what the generic code is allowed to do safely at compile time.

    Distinction: unmanaged permits low-level operations but does not promise a platform-independent layout or that every unmanaged type is blittable. notnull does not prevent a caller bypassing nullable warnings from passing null values; validate inputs when needed.

    Reference: Microsoft documentation.

    Question 15. What does scoped mean in ref-safe code?

    Answer: scoped (C# 11) restricts escape of a ref-like value or reference. A scoped ReadOnlySpan<char> parameter can be consumed in the method but cannot be returned as a span derived from that parameter; scoped ref T instead restricts escape of the reference. These are compile-time lifetime rules, not allocation or ownership instructions.

    Example:

    C#
    static void Print(scoped ReadOnlySpan<char> text)
    {
        Console.WriteLine(text.ToString());
        // Returning text as a ReadOnlySpan<char> from this method
        // (after changing its return type) would violate scoped escape rules.
    }

    A span is a view, not an owner. scoped does not extend backing storage lifetime or make the underlying data immutable. Ordinary heap-field storage of a span is already prohibited because it is a ref struct; that restriction is not introduced by scoped.

    Reference: Microsoft documentation.

    Question 16. What are readonly members in structs?

    Answer: readonly instance members (C# 8) promise not to mutate the struct instance. They can reduce defensive copies and communicate immutability intent for value types.

    C#
    public struct Point
    {
        public double X { get; init; }
        public double Y { get; init; }
        public readonly double Length => Math.Sqrt(X * X + Y * Y);
    }

    For a point with X = 3 and Y = 4, Length is 5. Calling a non-readonly member through a readonly receiver can require a defensive copy; marking a genuinely nonmutating member readonly avoids that copy in relevant contexts, not all copying. A readonly member may still mutate an object referenced by a field, so this is not deep immutability. Prefer readonly struct when the whole value should be immutable; the example’s init accessors require C# 9.

    Reference: Microsoft documentation.

    Compare your review comment

    A collection expression needs a target type and materializes its elements; it is not a promise of laziness or zero allocation. For 3 and 4, the shown Average<int> is 3, whereas Average<decimal> is 3.5. Choose the required numeric/rounding contract before changing syntax.

    Check the primary contract: Generic math.

    Check the decision

    The shown generic Average helper receives int values 3 and 4. A reviewer expects 3.5 because INumber<T> makes the method numeric. Which response is correct?

    A It returns 3.5 because a numeric generic constraint promotes division to double.
    B It returns 3: T remains int, so division uses integer arithmetic.
    C It throws because integer division cannot represent the fractional quotient.
    D It returns 4 because generic integer division rounds to the nearest integer.
    Show answer

    Correct answer: B

    INumber<T> enables operations for the chosen T; it does not change int into a fractional type. The shown decimal instantiation returns 3.5, subject to its own arithmetic/rounding requirements.

    Hint: Read Q1–2 for target typing/materialization and Q13 for the concrete numeric type. A generic constraint does not choose a business rounding policy.

    Sources

    Practice

    Practice test: Backend Interview Practice: Modern C# in Code Reviews5 questions · 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 ·