C# Method Parameters
A parameter is a variable named in a method definition. A call passes a value, called an argument, into the parameter.
One string parameter
Greet takes one string parameter. The call passes the name Hana as the argument.
using System;
class Program
{
static void Greet(string name)
{
Console.WriteLine("Hello, " + name);
}
static void Main(string[] args)
{
Greet("Hana");
}
}Return a sum
Add takes two int parameters. The return word sends the sum back and Main prints it.
using System;
class Program
{
static int Add(int a, int b)
{
return a + b;
}
static void Main(string[] args)
{
Console.WriteLine(Add(4, 5));
}
}Many values with params
Sum takes a params array of numbers. One call passes three values and the next call passes two values.
using System;
class Program
{
static int Sum(params int[] numbers)
{
int total = 0;
foreach (int num in numbers)
{
total += num;
}
return total;
}
static void Main(string[] args)
{
Console.WriteLine(Sum(1, 2, 3));
Console.WriteLine(Sum(4, 5));
}
}Default parameter value
ShowLevel has a default value of Beginner. A call can leave the argument out or pass its own value.
using System;
class Program
{
static void ShowLevel(string level = "Beginner")
{
Console.WriteLine("Level: " + level);
}
static void Main(string[] args)
{
ShowLevel();
ShowLevel("Advanced");
}
}Example
using System;
class Program
{
static double Total(double price, double tax)
{
return price + tax;
}
static void Main(string[] args)
{
double total = Total(50, 10);
Console.WriteLine("Total: " + total);
}
}Key points
- A parameter sits in parentheses after the method name.
- An argument is the value a call passes for a parameter.
- A method can take more than one parameter.
- The return keyword sends a value back to the caller.
- Use params before an array parameter to accept any count of values.
- A default value is used when a call leaves the argument out.
In this example, Total takes a price and a tax amount. Main passes 50 and 10 as the arguments. The method returns 60 as a double value. Main stores the value in total, and the print line shows Total: 60.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz C# Compiler
Exercise
What does a default parameter value do?