Named arguments let you say which value goes to which part of a method. This makes your code easier to read and understand.
0
0
Named arguments in C Sharp (C#)
Introduction
When a method has many parameters and you want to be clear about which value is for which parameter.
When you want to skip some optional parameters and only set specific ones.
When you want to improve code readability for others or yourself in the future.
Syntax
C Sharp (C#)
MethodName(parameterName: value, anotherParameter: value);
You write the name of the parameter, then a colon, then the value.
You can mix named and positional arguments, but positional ones must come first.
Examples
Call a method with named arguments for clarity.
C Sharp (C#)
PrintMessage(message: "Hello", times: 3);
Mix positional and named arguments. Positional first, then named.
C Sharp (C#)
PrintMessage("Hello", times: 3);
Named arguments can be in any order.
C Sharp (C#)
PrintMessage(times: 3, message: "Hello");
Sample Program
This program shows how to use named arguments to call the PrintMessage method in different ways.
C Sharp (C#)
using System; class Program { static void PrintMessage(string message, int times) { for (int i = 0; i < times; i++) { Console.WriteLine(message); } } static void Main() { // Using named arguments PrintMessage(message: "Hi!", times: 2); // Mixing positional and named arguments PrintMessage("Hello", times: 3); // Named arguments in different order PrintMessage(times: 1, message: "Bye!"); } }
OutputSuccess
Important Notes
Named arguments improve code readability, especially with many parameters.
Positional arguments must come before named arguments in a method call.
Named arguments allow skipping optional parameters by naming only those you want to set.
Summary
Named arguments let you specify which parameter gets which value by name.
You can mix named and positional arguments, but positional must come first.
This helps make your code easier to read and understand.