Lesson 27 +10 XP

Method Parameters & Return Values

Method Parameters & Return Values

Parameters let you pass information into a method. Return values let a method hand data back.

Parameters

Information is passed to a method inside the parentheses:

static void MyMethod(string fname)
{
  Console.WriteLine(fname + " Refsnes");
}

static void Main(string[] args)
{
  MyMethod("Liam");
  MyMethod("Jenny");
}

Output:

Liam Refsnes
Jenny Refsnes

Multiple parameters

static void MyMethod(string fname, int age)
{
  Console.WriteLine(fname + " is " + age);
}

When calling, pass values in the same order: MyMethod("Liam", 24);.

Default parameter values

Give a parameter a default with =. If no value is passed, the default is used:

static void MyMethod(string country = "Norway")
{
  Console.WriteLine(country);
}

MyMethod("Sweden");  // Sweden
MyMethod();          // Norway

Return values

Instead of void, declare the return type and use return:

static int MyMethod(int x)
{
  return 5 + x;
}

static void Main(string[] args)
{
  Console.WriteLine(MyMethod(3));   // 8
}

Named arguments

You can pass arguments by name, in any order:

static void MyMethod(string child1, string child2, string child3)
{
  Console.WriteLine("The youngest child is: " + child3);
}

MyMethod(child3: "John", child1: "Liam", child2: "Jenny");

TL;DR

  • Parameters are values you pass in.
  • Defaults kick in when no value is passed.
  • return sends a value back; the return type replaces void.
  • Named arguments can be passed in any order.