C# Programming Tutorial 0/45 lessons ~6 min read Lesson 13

    Method Overloading

    Overloading defines multiple methods with the same name but different parameter lists — count, types, or ref kinds.

    Course progress0%
    Focus
    10 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    Overloading defines multiple methods with the same name but different parameter lists — count, types, or ref kinds. The compiler resolves the best match at compile time (static dispatch), unlike virtual override which is runtime polymorphism.

    Frameworks overload extensively: Console.WriteLine has dozens of variants; LINQ Where accepts different delegate types. Misusing overloads for unrelated behaviors confuses API consumers — prefer distinct names when semantics differ.

    Interviewers ask about ambiguity errors when two overloads match equally well and how optional parameters interact with overload resolution.

    The story

    A hospital appointment system sends notifications to patients — a single SMS, a bulk email blast to a list of recipients, or a templated message with personalized fields like doctor name and appointment time. Callers use the same Send method name; the compiler picks the right overload based on argument types.

    Overloading keeps the API discoverable while the implementation delegates to a single core path internally.

    Understanding the topic

    Key concepts

    • Overload resolution picks most specific applicable method.
    • Return type alone does not distinguish overloads.
    • params array is least preferred in resolution.
    • Optional parameters compile to multiple call forms.
    • Generic methods participate in overload resolution with type inference.
    • Explicit interface implementation can duplicate names across interfaces.

    Step-by-step explanation

    1. Compiler builds candidate set matching name and accessibility.
    2. Eliminate methods with incompatible arguments.
    3. Prefer non-params over params; fewer conversions wins.
    4. Ambiguity CS0121 when two equally specific — fix signatures.
    5. Cast arguments to disambiguate intentionally.
    6. Runtime still uses virtual dispatch for overridden instance methods.

    Practical code example

    Overloaded notification senders for email, SMS, and batch — enterprise alert gateway:

    csharp
    namespace TechLearningPro.Overloading;
    public interface INotificationGateway
    {
    void Send(string recipient, string message);
    void Send(IReadOnlyList<string> recipients, string message);
    void Send(string recipient, string templateId, IReadOnlyDictionary<string, string> data);
    }
    public sealed class NotificationGateway : INotificationGateway
    {
    public void Send(string recipient, string message) =>
    Console.WriteLine(
    quot;To {recipient}: {message}");
    public void Send(IReadOnlyList<string> recipients, string message)
    {
    foreach (var r in recipients)
    Send(r, message);
    }
    public void Send(string recipient, string templateId, IReadOnlyDictionary<string, string> data) =>
    Console.WriteLine(
    quot;To {recipient} template {templateId} with {data.Count} fields");
    }

    Line-by-line code explanation

    • interface INotificationGateway declares three Send overloads with different parameter lists.
    • void Send(string recipient, string message) handles a single plain-text notification.
    • void Send(IReadOnlyList<string> recipients, string message) accepts many recipients at once.
    • void Send(string recipient, string templateId, IReadOnlyDictionary<string, string> data) supports templated messages.
    • public void Send(string recipient, string message) => implements the simplest overload with an expression body.
    • foreach (var r in recipients) Send(r, message) delegates the batch overload to the single-recipient version.
    • Console.WriteLine($"To {recipient} template {templateId}...") logs templated sends with field counts.
    • IReadOnlyList and IReadOnlyDictionary prevent callers from mutating internal collections.

    Key takeaway: Batch overload delegates to single-recipient overload — DRY. Template overload adds structured data without breaking existing callers.

    Real-world use

    Where you'll use this in production

    • Logging extensions with varying parameter counts.
    • Factory methods Create(id) vs Create(options).
    • Math utilities Abs(int), Abs(decimal).
    • ASP.NET Results Ok(), Ok(object), Created().

    Best practices

    • Overload when semantics identical, inputs differ in shape.
    • Avoid overloads differing only by optional params confusion.
    • Document which overload is preferred entry point.
    • Chain overloads to simplest implementation.
    • Use distinct names when behavior fundamentally differs.

    Common mistakes

    • Ambiguous call CS0121 with int vs long literals.
    • Adding overload breaking binary compatibility unexpectedly.
    • Overloading on bool vs int legacy APIs.
    • params overload hiding more specific overloads.

    Advanced interview questions

    Q1BeginnerWhat makes a valid overload?
    Same name, different parameter list; same class or static context.
    Q2BeginnerCan overload differ only by return type?
    No — compile error; signature excludes return type.
    Q3IntermediateHow resolve ambiguous overload?
    Change argument types, add parameter, or rename one method.
    Q4IntermediateOverload vs override?
    Overload: same class, compile-time; override: inheritance, runtime virtual dispatch.
    Q5AdvancedDesign FileLogger Write overloads for string, byte[], and structured object.
    Write(string), Write(ReadOnlySpan), Write(T obj) using serializer; avoid bool ambiguity; document UTF-8 for bytes.

    Summary

    Overloading provides multiple signatures for one method name. Compiler picks best match; ambiguity requires signature fixes. Chain complex overloads to simpler core implementations. Do not confuse with overriding virtual methods. Next: classes and objects — OOP foundation.

    Ready to mark this lesson complete?Track your journey across the entire course.