Named Arguments
Part of the Object Oriented Programming section of Coddy's C# journey — lesson 49 of 70.
Named arguments let you specify which parameter receives a value by using its name, rather than relying on position. This makes method calls clearer and allows you to pass arguments in any order.
Use the parameter name followed by a colon before the value:
public static void CreateUser(string name, int age, bool isActive)
{
Console.WriteLine($"{name}, Age: {age}, Active: {isActive}");
}
// Using named arguments
CreateUser(name: "Alice", age: 25, isActive: true);
CreateUser(age: 30, isActive: false, name: "Bob"); // Any order worksNamed arguments shine when combined with optional parameters. Instead of providing all preceding optional values, you can skip directly to the one you need:
public static void Configure(string host, int port = 8080, bool useSSL = false, int timeout = 30)
{
Console.WriteLine($"{host}:{port}, SSL: {useSSL}, Timeout: {timeout}");
}
// Skip port and useSSL, only specify timeout
Configure("localhost", timeout: 60);
Configure("server.com", useSSL: true);You can mix positional and named arguments, but positional arguments must come first. Named arguments improve readability, especially for methods with multiple parameters of the same type or boolean flags where the meaning isn't obvious from the value alone.
Challenge
EasyLet's build a report generator that takes advantage of named arguments to make method calls crystal clear. When methods have multiple parameters - especially ones of the same type or boolean flags - named arguments make your code self-documenting.
You'll organize your code across two files:
ReportGenerator.cs: Create aReportGeneratorclass in theReportsnamespace with a method that has several optional parameters:GenerateReport(string title, string author = "Anonymous", bool includeHeader = true, bool includeSummary = false, int maxPages = 10)- This method should return a formatted string describing the report configuration
- Format:
Report: {title} by {author} | Header: {Yes/No}, Summary: {Yes/No}, Max Pages: {maxPages}
Program.cs: In your main file, demonstrate the power of named arguments by callingGenerateReportin different ways - skipping optional parameters you don't need and specifying only the ones that matter for each report.
You will receive three inputs:
- First report title
- Second report title
- Third report title
Generate three reports with different configurations:
- First report: Use only the title (all defaults apply)
- Second report: Use the title with
includeSummary: trueandmaxPages: 25(skip author and includeHeader, keeping their defaults) - Third report: Use the title with
author: "Admin",includeHeader: false, andincludeSummary: true(keep maxPages default)
Print each report result on its own line.
For example, if the inputs are Sales Q1, Annual Review, and Inventory Check, the output should be:
Report: Sales Q1 by Anonymous | Header: Yes, Summary: No, Max Pages: 10
Report: Annual Review by Anonymous | Header: Yes, Summary: Yes, Max Pages: 25
Report: Inventory Check by Admin | Header: No, Summary: Yes, Max Pages: 10Notice how named arguments let you skip directly to the parameters you care about - you don't have to specify author or includeHeader just to change includeSummary. This makes your method calls much more readable and intention-revealing!
Cheat sheet
Named arguments allow you to specify which parameter receives a value by using its name, rather than relying on position. This makes method calls clearer and allows you to pass arguments in any order.
Use the parameter name followed by a colon before the value:
public static void CreateUser(string name, int age, bool isActive)
{
Console.WriteLine($"{name}, Age: {age}, Active: {isActive}");
}
// Using named arguments
CreateUser(name: "Alice", age: 25, isActive: true);
CreateUser(age: 30, isActive: false, name: "Bob"); // Any order worksNamed arguments work well with optional parameters. You can skip directly to the parameter you need without providing all preceding optional values:
public static void Configure(string host, int port = 8080, bool useSSL = false, int timeout = 30)
{
Console.WriteLine($"{host}:{port}, SSL: {useSSL}, Timeout: {timeout}");
}
// Skip port and useSSL, only specify timeout
Configure("localhost", timeout: 60);
Configure("server.com", useSSL: true);You can mix positional and named arguments, but positional arguments must come first. Named arguments improve readability, especially for methods with multiple parameters of the same type or boolean flags.
Try it yourself
using System;
using Reports;
class Program
{
public static void Main(string[] args)
{
// Read the three report titles
string title1 = Console.ReadLine();
string title2 = Console.ReadLine();
string title3 = Console.ReadLine();
// Create a ReportGenerator instance
ReportGenerator generator = new ReportGenerator();
// TODO: Generate first report - use only the title (all defaults apply)
// TODO: Generate second report - use title with includeSummary: true and maxPages: 25
// (skip author and includeHeader, keeping their defaults)
// TODO: Generate third report - use title with author: "Admin", includeHeader: false, and includeSummary: true
// (keep maxPages default)
// Print each report result
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesNamespaces & DirectivesIntro to Classes & ObjectsThe 'this' KeywordMethods and ParametersFields vs PropertiesConstructorsObject InitializersRecap - Simple Calculator4Inheritance
Basic Inheritance (:) SyntaxThe 'base' KeywordVirtual & Override KeywordsSealed ClassesThe 'object' Base ClassRecap - Employee Hierarchy7Advanced Features
Operator OverloadingIndexers (this[])ToString() OverrideExtension MethodsRecap - Custom List2Properties & Static Members
Auto-Implemented PropertiesRead/Write-Only PropertiesStatic Fields & MethodsStatic ClassesExpression-Bodied Members5Polymorphism & Interfaces
Compile vs Runtime PolyInterface vs Abstract ClassMultiple InterfacesExplicit InterfacesUpcasting & DowncastingRecap - Shape Calculator