C# Method Parameters

Methods become far more useful when you can pass information into them. Values passed into a method are called parameters when you define the method, and arguments when you actually call it. Parameters let one method work with many different inputs.

Adding a Parameter

A parameter is written inside the parentheses as a type followed by a name. Inside the method you use the parameter like a normal variable. When you call the method, you supply an argument that fills in that parameter.

A method with one parameter

static void Greet(string name)
{
    Console.WriteLine("Hello " + name);
}

static void Main()
{
    Greet("Liam");   // Hello Liam
    Greet("Noor");   // Hello Noor
}

Multiple Parameters

You can pass as many parameters as you need by separating them with commas. When you call the method, the arguments must be given in the same order as the parameters were declared.

Two parameters

static void Introduce(string name, int age)
{
    Console.WriteLine(name + " is " + age + " years old.");
}

static void Main()
{
    Introduce("Ava", 30); // Ava is 30 years old.
}

Default Parameter Values

You can give a parameter a default value by assigning it in the method definition. If you leave out that argument when calling the method, the default value is used instead.

A parameter with a default value

static void Greet(string name = "friend")
{
    Console.WriteLine("Hello " + name);
}

static void Main()
{
    Greet();        // Hello friend
    Greet("Sara");  // Hello Sara
}

Parameter vs argument

TermMeaning
ParameterThe variable listed in the method definition
ArgumentThe actual value you pass when calling the method
Note: Arguments must match the parameter types. Passing a string where an int is expected will cause a compile error, so the mistake is caught before your program runs.