CodeBlanks Logo Icon CodeBlanks

Parameterized methods

C# course · Beginner · Lesson 77/116

Learn methods that take parameters and how to call them.

Parameterized methods

The values a method takes are declared as parameters inside its parentheses. Each parameter has a type and a name: static void Greet(string name). Here the name parameter is of type string.

When calling, you write an argument inside the parentheses: Greet("Ayşe"). The argument is copied into the parameter and used as name in the body. The number and type of arguments must match the parameters exactly.

Passing arguments

The value you write inside the parentheses at the call site is the argument. Its order and type must match the parameters exactly. The first argument maps to the first parameter, the second to the second.

For example, the method static void Show(string label, int value) is called as Show("Score", 85). Here label = "Score" and value = 85. A type or order mismatch gives a compile error.

Exercise Greeting method

Define a static void Greet(string name) method; in the body write Console.WriteLine("Hello, " + name). In Main, call Greet("Ayşe").

Show example solution
Add Console.WriteLine("Hello, " + name); to the Greet body, write Greet("Ayşe"); in Main.
Example solution:
using System;

class Program
{
    static void Greet(string name)
    {
        // Print a greeting message
        Console.WriteLine("Hello, " + name);
    }

    static void Main()
    {
        // Call Greet
        Greet("Ayşe");
    }
}

Test yourself

  1. Declare a parameter

    static void Greet(____)
    {
        Console.WriteLine(name);
    }
    Show answer
    static void Greet(string name)
    {
        Console.WriteLine(name);
    }
  2. What does ShowNumber(42) print?

    static void ShowNumber(int n)
    {
        Console.WriteLine(n);
    }
    ShowNumber(42);
    • 0
    • 42
    • n
    • ShowNumber
    Show answer

    42 — Correct. 42 is copied into n; Console prints 42.

  3. Match each expression to its meaning

    string name
    Text parameter
    int n
    Integer parameter
    Greet("Ayşe")
    Call + argument
    static void
    No return value

All lessons in Beginner