Methods get data through parameters. You can pass values in, pass references around, and even get multiple values back. Let's see how.
Parameters and Arguments
Define parameters in the method signature. When you call the method, the values you pass are the arguments. They get copied into the parameters.
using System;
class Program {
static void Greet(string name) {
Console.WriteLine("Hi, " + name);
}
static void Main() {
Greet("Alice");
Greet("Bob");
}
}
Try it Yourself →
Default Parameters
Give a parameter a default value with =. If the caller skips that argument, the default is used.
using System;
class Program {
static void PrintMessage(string text, int times = 1) {
for (int i = 0; i < times; i++) {
Console.WriteLine(text);
}
}
static void Main() {
PrintMessage("Hello");
PrintMessage("Hi", 3);
}
}
Try it Yourself →
The ref Keyword
ref passes a reference to the original variable. Changes inside the method affect the original outside.
using System;
class Program {
static void Double(ref int x) {
x = x * 2;
}
static void Main() {
int number = 5;
Double(ref number);
Console.WriteLine(number);
}
}
Try it Yourself →
The out Keyword
out is like ref, but you don't need to initialize the variable before passing it. The method must assign a value before returning.
using System;
class Program {
static void Divide(int a, int b, out int quotient, out int remainder) {
quotient = a / b;
remainder = a % b;
}
static void Main() {
int q, r;
Divide(10, 3, out q, out r);
Console.WriteLine(q + " remainder " + r);
}
}
Try it Yourself →
Named Arguments
Specify which parameter you're filling by name. Lets you skip optional parameters or make your intent clearer.
using System;
class Program {
static void BookFlight(string destination, int seats = 1, bool insured = false) {
Console.WriteLine($"Flight to {destination}, {seats} seat(s), insured: {insured}");
}
static void Main() {
BookFlight("Paris", insured: true);
BookFlight(destination: "London", seats: 2);
}
}
Try it Yourself →