Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close
    Lesson3 / 22

    Module 2 · Object-oriented C#, delegates and generics · Lesson 3 of 22

    OOP, delegates, generics, and reflection

    Start here: Which delivery message prints?

    C#
    Delivery delivery = new ExpressDelivery();
    Console.WriteLine(delivery.Label()); // Express
    
    class Delivery
    {
        public virtual string Label() => "Standard";
    }
    
    class ExpressDelivery : Delivery
    {
        public override string Label() => "Express";
    }

    The variable is declared as Delivery, which tells the compiler that calling Label() is allowed. The object is an ExpressDelivery. Because Label is virtual and overridden, that object supplies the implementation at runtime. This is polymorphism: the caller uses one method through a common type, while different objects provide different behavior.

    If ExpressDelivery uses new instead of override in the example, what does the existing call print?

    A Express
    B Standard
    C Both messages
    D The assignment no longer compiles
    Show answer

    Correct answer: B

    new hides the base member rather than overriding it. The existing call is through a Delivery reference, so it calls the base implementation.

    Hint: Follow the declared type when a member is hidden rather than overridden.

    Microsoft Learn: override versus new

    Attempt before the reference answer

    An event has three handlers in order: write A, throw, write C. Trace a normal multicast invocation before running the retained example. Then explain what contract would have to change if every handler must be attempted even when one fails.

    Trace to compare

    StepNormal multicast invocationDesign decision
    First handlerWrites ANo failure yet
    Second handlerThrows; invocation stopsCaller decides how to observe the failure
    Third handlerIs not invoked on this pathContinuing requires an explicit per-handler policy; it is not automatic

    Decision check

    With a normal multicast delegate, the second handler throws and the caller catches it. What happens to the third handler?

    A It is skipped on that invocation.
    B It always runs in finally.
    C The runtime retries it on the thread pool.
    D It runs before the exception reaches the caller.
    Show answer

    Correct answer: A

    A normal multicast invocation stops when a handler throws. A design that attempts each handler needs explicit invocation-list iteration and an error policy; that changes the behavior.

    Option B: There is no automatic finally around each later handler.

    Option C: The delegate does not schedule a retry.

    Option D: The exception interrupts normal invocation before the third call.

    Hint: Follow the call sequence until control leaves the invocation.

    Reference questions

    Before you start

    Know classes, method calls and the difference between a value and an object reference from Core Basics.

    This lesson covers contracts and callbacks, generic type safety, equality, and metadata and design choices. For each question, give the short answer first, then explain the example or trade-off.

    Examples are independent snippets for .NET 8 / C# 12 or later, with nullable reference types enabled. Q32 shows type declarations rather than a complete console program. Version-specific behavior is called out where relevant.

    Question 31. Interface vs abstract class?

    An app needs to print a sales report or show a preview. The caller should be able to ask either exporter for a result without knowing how it formats the report.

    Interview answer: An interface defines what the caller can ask for, even when the implementations are unrelated. An abstract class is a base for related types that need shared implementation or instance state. A class can implement multiple interfaces but inherit only one base class.

    C#
    using System;
    
    IReportExporter[] exporters = { new TextReportExporter(), new PreviewExporter() };
    foreach (var exporter in exporters)
        Console.WriteLine(exporter.Export("Sales"));
    // Report: Sales
    // Preview: Sales
    
    interface IReportExporter
    {
        string Export(string title);
    }
    
    abstract class ReportExporter : IReportExporter
    {
        protected static string Header(string title) => $"Report: {title}";
        public abstract string Export(string title);
    }
    
    sealed class TextReportExporter : ReportExporter
    {
        public override string Export(string title) => Header(title);
    }
    
    sealed class PreviewExporter : IReportExporter
    {
        public string Export(string title) => $"Preview: {title}";
    }

    Why: Both objects satisfy IReportExporter, so the loop calls Export the same way on each. TextReportExporter reuses the base class’s header helper; PreviewExporter uses the same contract without inheriting the helper. The base shares code here, but could also hold instance state.

    Choose: Start with an interface when callers need a common contract. Use an abstract base when related implementations have behavior or state worth sharing. Since C# 8, interfaces can provide default implementations, but they still cannot contain instance fields.

    Read more: Interfaces.

    Question 32. Why can a public class not derive from an internal base class?

    Answer: Public APIs cannot expose less-accessible types. If a public class derived from an internal base type, external callers would see a public type whose inheritance contract depends on a type they cannot access.

    C#
    internal class InternalBase { }
    // Invalid if exposed publicly:
    // public class PublicChild : InternalBase { }

    Question 33. What are delegates, events, Func, Action, and Predicate?

    Interview answer: A delegate is a type-safe callable reference to one or more methods. Func returns a value, Action returns void, and Predicate<T> returns bool. An event exposes subscription: outside code can add/remove handlers, but cannot invoke it or replace its invocation list.

    C#
    using System;
    
    Func<int, int, int> add = (x, y) => x + y;
    Action<string> log = message => Console.WriteLine(message);
    Predicate<int> isEven = x => x % 2 == 0;
    log($"{add(2, 3)}, {isEven(4)}"); // 5, True
    
    var orders = new OrderService();
    orders.OrderCreated += (_, _) => log("Order created");
    orders.CreateOrder(); // Order created
    
    public sealed class OrderService
    {
        public event EventHandler? OrderCreated;
        public void CreateOrder() => OrderCreated?.Invoke(this, EventArgs.Empty);
    }

    Why: Calling CreateOrder lets the publisher raise its own event; subscribers cannot call orders.OrderCreated.Invoke(...). Use events for notifications and delegates for pluggable behavior.

    Read more: Delegates and events.

    Question 34. Can Func use out parameters?

    Answer: No. Built-in Func and Action delegate types do not support ref, out, or in parameter modifiers. Declare a custom delegate.

    C#
    using System;
    
    TryParseDelegate parser = int.TryParse;
    bool ok = parser("123", out int value);
    Console.WriteLine($"{ok}, {value}"); // True, 123
    
    public delegate bool TryParseDelegate(string input, out int value);

    Why: The custom signature matches int.TryParse(string, out int). Func<string, int, bool> would take its int by value, not write back to the caller. The in/out on generic variance declarations in Q38 are different from parameter modifiers.

    Read more: Func signature and parameter modifiers.

    Question 35. What happens if one handler in a multicast delegate throws?

    Interview answer: During ordinary synchronous multicast invocation, handlers run in invocation-list order. An uncaught exception stops invocation and propagates to the caller; later handlers do not run.

    C#
    using System;
    
    Action handlers = () => Console.WriteLine("First");
    handlers += () => throw new InvalidOperationException("Failed");
    handlers += () => Console.WriteLine("Last");
    try { handlers(); }
    catch (InvalidOperationException) { Console.WriteLine("Caught"); }
    // Output: First, then Caught on separate lines. No Last.

    Why: Catching around the combined call does not resume its remaining handlers. If every handler must be attempted, iterate GetInvocationList() and handle failures separately with an explicit reporting policy. Do not silently swallow errors. This example does not describe exceptions from async void handlers.

    Read more: Multicast invocation behavior.

    Question 36. What are ref, out, and in parameters?

    Interview answer: ref lets the callee read/write the caller's initialized variable. out does not require initialization by the caller, but the callee must assign it before returning normally. in provides readonly access through the parameter; it does not make a referenced object immutable.

    C#
    using System;
    
    int number = 1;
    Increment(ref number);
    TryGet(out int value);
    Print(in number);              // 2
    Console.WriteLine(value);      // 42
    
    static void Increment(ref int x) => x++;
    static bool TryGet(out int value)
    {
        value = 42;
        return true;
    }
    static void Print(in int x) => Console.WriteLine(x);

    Why: Increment changes the original variable; TryGet initializes value. Print can read number but cannot assign to x. At the call site, ref and out are required; in is usually optional.

    Trade-off: in can reduce copying for large structs, but compiler-generated temporaries or defensive copies can offset the benefit. Measure before treating it as a performance improvement.

    Read more: Method parameters.

    Question 37. What are generics and why use them?

    Interview answer: Generics let you write reusable types and methods with compile-time type checking. A List<int> stores integers without boxing each element as an object; generic code is not automatically allocation-free or boxing-free.

    C#
    using System;
    using System.Collections.Generic;
    
    var numbers = new Repository<int>();
    numbers.Add(42);
    Console.WriteLine(numbers.Items[0]); // 42
    // numbers.Add("42");               // Compile-time error if uncommented
    
    public sealed class Repository<T>
    {
        private readonly List<T> _items = new();
        public void Add(T item) => _items.Add(item);
        public IReadOnlyList<T> Items => _items;
    }

    Why: Choosing T = int makes Add accept an int and the indexer return an int, without a cast. Items is a read-only interface to the list, not an immutable snapshot.

    Read more: Generic types and methods.

    Question 38. What is covariance and contravariance?

    Interview answer: You can read a sequence of strings as a sequence of objects. That is covariance: the producer supplies something more specific than the caller requires. You can also use a handler that accepts any object where you only need it to handle strings. That is contravariance: the handler accepts more than the caller needs to pass.

    C#
    using System;
    using System.Collections.Generic;
    
    IEnumerable<string> strings = new List<string> { "hello" };
    IEnumerable<object> objects = strings; // covariance: out T
    foreach (object item in objects)
        Console.WriteLine($"Read as object: {item}"); // Read as object: hello
    
    Action<object> handleObject = o => Console.WriteLine($"Handled as object: {o}");
    Action<string> handleString = handleObject; // contravariance: in T
    handleString("hello"); // Handled as object: hello

    Why: Every string produced is an object. A handler accepting any object can safely accept a string. Variant generic parameters belong to interfaces/delegates and these conversions apply to reference types: IEnumerable<int> cannot become IEnumerable<object> this way. List<T> remains invariant.

    Read more: Covariance and contravariance.

    Question 39. Why does IList<IList<int>> not accept List<List<int>>?

    Answer: Generic collections like IList<T> are invariant because they allow both reading and writing. If assignment were allowed, code could insert a different implementation of IList<int> into a List<List<int>>, breaking type safety.

    C#
    using System;
    using System.Collections.Generic;
    
    List<List<int>> concrete = new() { new List<int> { 1 } };
    // IList<IList<int>> invalid = concrete; // Compile-time error
    IEnumerable<IList<int>> view = concrete; // Valid covariance
    foreach (IList<int> row in view)
        row.Add(2);
    Console.WriteLine(concrete[0].Count); // 2

    Why: The outer IEnumerable cannot insert a new row, so the conversion is safe. Its inner IList<int> values are still mutable, which explains the count of 2. If you need writable interface-typed rows, create List<IList<int>> from the start. A cast cannot make the original nested list invariantly compatible.

    Read more: Variance in generic interfaces.

    Question 40. Why must Equals and GetHashCode be overridden together?

    Answer: Hash-based collections use hash code to find a bucket and equality to confirm the match. If two objects are equal, they must return the same hash code.

    C#
    using System;
    using System.Collections.Generic;
    
    var key = new EmployeeKey(7, 42);
    var names = new Dictionary<EmployeeKey, string> { [key] = "Ada" };
    Console.WriteLine(names[new EmployeeKey(7, 42)]); // Ada
    
    public sealed record EmployeeKey(int CompanyId, int EmployeeId);

    Why: Records generate compatible value equality and hash codes, so the new key finds the original entry. For manual implementations, keep equality and hashing consistent. Do not mutate equality-relevant state while an object is a dictionary key; lookup can fail even though the entry remains stored.

    Read more: Equality and hashing contract and records.

    Question 41. Is a hash code unique?

    Answer: No. Two unequal values can have the same hash code. That is a collision. A hash-based collection uses the hash to narrow the search and the equality comparer to decide whether a candidate actually matches.

    C#
    using System;
    using System.Collections.Generic;
    
    var comparer = new ConstantHashComparer();
    var names = new HashSet<string>(comparer) { "Ada", "Grace" };
    
    Console.WriteLine(comparer.GetHashCode("Ada") == comparer.GetHashCode("Grace")); // True
    Console.WriteLine(names.Count); // 2
    Console.WriteLine(names.Contains("Linus")); // False
    
    sealed class ConstantHashComparer : IEqualityComparer<string>
    {
        public bool Equals(string? x, string? y) => StringComparer.Ordinal.Equals(x, y);
        public int GetHashCode(string obj) => 0; // Deliberately poor: demo only
    }

    Why: Ada and Grace have the same hash here, but ordinal equality says they are different, so the set keeps both. Linus also has the same hash and still does not match. A constant hash obeys the equality contract but ruins distribution and can make lookups slow. Use it only for this demo. Do not persist GetHashCode() values as IDs or use them as cryptographic hashes; they need not be stable across processes or runtime versions.

    Read more: GetHashCode guarantees and limits.

    Question 42. Why do hash algorithms often use prime numbers?

    Interview answer: Primes are useful in some hash-table sizing and probing strategies, but they do not guarantee unique hashes or eliminate collisions. The benefit depends on the algorithm, not simply on choosing a prime.

    For example, a prime table size helps a double-hashing probe visit every bucket when its step is nonzero modulo that size. This is one implementation technique, not a C# requirement. For application value objects, prefer HashCode.Combine over hand-rolled arithmetic, while preserving Q40's equality contract.

    Read more: .NET hash-table helper rationale and HashCode.

    Question 43. What is [Serializable] and when should it be used?

    Interview answer: [Serializable] marks a type for serializers that honor that metadata, notably legacy formatter-based serialization. Use it when a required serializer contract calls for it, not as a default DTO annotation. System.Text.Json does not require it.

    C#
    using System;
    using System.Text.Json;
    
    var message = new Message { Text = "Hello" };
    Console.WriteLine(JsonSerializer.Serialize(message)); // {"Text":"Hello"}
    
    public sealed class Message
    {
        public string Text { get; set; } = "";
    }

    Why: System.Text.Json serializes this public property without [Serializable]. Configure the chosen serializer's contract and options instead.

    Legacy warning: Do not introduce BinaryFormatter; it is insecure. In .NET 9 and later, the in-box implementation throws PlatformNotSupportedException, even with the old compatibility switch enabled.

    Read more: SerializableAttribute, JSON serialization and BinaryFormatter migration.

    Question 44. What does [Flags] do on an enum?

    Interview answer: [Flags] indicates that an enum represents combinable bit flags. Give independent flags powers of two; zero represents none, and named combinations need not be powers of two. The attribute does not validate values or enable the bitwise operators.

    C#
    using System;
    
    var permissions = Permissions.Read | Permissions.Write;
    Console.WriteLine(permissions.HasFlag(Permissions.Write)); // True
    Console.WriteLine(permissions == Permissions.None);        // False
    
    [Flags]
    public enum Permissions
    {
        None = 0,
        Read = 1,
        Write = 2,
        Delete = 4,
        ReadWrite = Read | Write
    }

    Why: 1 | 2 sets both bits. To test for no permissions, compare with None; HasFlag(None) returns true for every value because it tests a zero-bit mask.

    Read more: Flags enums and HasFlag.

    Question 45. What are attributes and how do you read them?

    Answer: Attributes attach metadata to code. You can read them with reflection.

    C#
    using System;
    using System.Linq;
    
    var method = typeof(OrderService).GetMethod(nameof(OrderService.CreateOrder));
    var audit = method?.GetCustomAttributes(typeof(AuditAttribute), false)
                       .Cast<AuditAttribute>()
                       .FirstOrDefault();
    Console.WriteLine(audit?.Action); // Create order
    
    [AttributeUsage(AttributeTargets.Method)]
    public sealed class AuditAttribute : Attribute
    {
        public string Action { get; }
        public AuditAttribute(string action) => Action = action;
    }
    
    public sealed class OrderService
    {
        [Audit("Create order")]
        public void CreateOrder() { }
    }

    Why: Reflection locates the public method and retrieves its AuditAttribute, whose constructor argument supplies the printed action. Adding [Audit] does not automatically implement auditing; application or framework code must interpret the metadata.

    Read more: Reading attributes.

    Question 46. How costly is reflection and when is it appropriate?

    Interview answer: Reflection inspects types and members at runtime and can invoke them dynamically. Repeated member lookup and reflective invocation can cost more than direct calls; the cost depends on the operation and runtime, so avoid quoting a universal slowdown factor.

    Choose: Reflection fits serializers, dependency-injection frameworks, plugins, attributes and tooling. Cache discovered metadata when reused, and keep repeated lookup out of hot loops. Caching lookup does not remove every invocation cost; measure the actual path.

    Deployment pitfall: Trimming can remove members reached only dynamically. Use supported annotations or statically analyzable alternatives, and test the published application rather than assuming a debug build proves compatibility.

    Read more: Reflection, runtime performance improvements and trimming guidance.

    Question 47. What is Activator.CreateInstance?

    Interview answer: Activator.CreateInstance creates an instance of a specified type. The Type overload is useful when the type is selected at runtime; for a class, the simple overload below invokes its public parameterless constructor.

    C#
    using System;
    using System.Text;
    
    Type type = typeof(StringBuilder);
    var builder = (StringBuilder)Activator.CreateInstance(type)!;
    builder.Append("Hello");
    Console.WriteLine(builder.ToString()); // Hello

    Why: The created object is a StringBuilder; the cast gives access to its normal API. Construction can fail if the type is abstract, the required constructor is missing, or the constructor throws. Prefer new, factories or dependency injection when the type is already known.

    Read more: Activator.CreateInstance.

    Question 48. What is a DLL vs an EXE?

    Answer: An executable launches an application, while a library supplies reusable code. File extensions alone do not identify the managed role: modern .NET can run an application assembly with dotnet MyApp.dll, and its platform-specific apphost executable is a native launcher, not itself the managed assembly.

    Example: A web API project may compile to an executable host and reference several DLL class libraries for services, data access, and domain logic.

    Question 49. What is a design pattern?

    Scenario: Your checkout calculates shipping differently for standard and express delivery. Instead of scattering those rules throughout checkout, have checkout call rate.Calculate(order), where rate implements IShippingRate. The caller supplies a standard or express implementation; checkout calls it the same way. That is Strategy: interchangeable ways to perform the same operation.

    Interview answer: A design pattern is a reusable approach to a recurring design problem, not a fixed piece of code. Strategy is useful when pricing rules change independently or need separate tests. If the only two rules are short and stable, a simple switch can be clearer.

    Other patterns: Factory centralizes creation decisions, Adapter translates between interfaces, Repository provides a boundary around data access, and Decorator wraps an object to add behavior while preserving its interface.

    Design Patterns in C#: The .NET Interview Guide

    Quick recall

    Before looking back, explain:

    1. Why can a subscriber attach a handler but not raise the event? (Q33)
    2. Why does catching a multicast exception not run the remaining handlers? (Q35)
    3. Why is the outer conversion in Q39 safe even though the inner lists can change?
    4. What must equal dictionary keys agree on, and what does a matching hash not prove? (Q40–41)
    5. Why does adding [Audit] or [Serializable] not automatically provide the behavior its name suggests? (Q43, Q45)

    If an answer is unclear, revisit that example and explain its result aloud before moving on.

    Practice

    Practice test: C# Interview Practice: OOP, Delegates, Generics, and Reflection5 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 28 Oct 2026 ·