0
0
C Sharp (C#)programming~5 mins

Parameters and arguments in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Parameters let you send information into a method. Arguments are the actual values you give when calling the method.

When you want a method to work with different data each time it runs.
When you want to reuse code but with different inputs.
When you want to make your methods flexible and easy to understand.
Syntax
C Sharp (C#)
void MethodName(type parameterName) {
    // method body
}

// Calling the method
MethodName(argumentValue);

Parameters are like placeholders inside the method.

Arguments are the real values you send to the method when you call it.

Examples
This method takes one parameter name and prints a greeting. We call it with the argument "Alice".
C Sharp (C#)
void Greet(string name) {
    Console.WriteLine($"Hello, {name}!");
}

Greet("Alice");
This method takes two parameters and returns their sum. We call it with arguments 3 and 5.
C Sharp (C#)
int Add(int a, int b) {
    return a + b;
}

int result = Add(3, 5);
Console.WriteLine(result);
Sample Program

This program defines a method PrintSum with two parameters. It prints the sum of the two numbers. We call it twice with different arguments.

C Sharp (C#)
using System;

class Program {
    static void PrintSum(int x, int y) {
        int sum = x + y;
        Console.WriteLine($"Sum of {x} and {y} is {sum}");
    }

    static void Main() {
        PrintSum(4, 7);
        PrintSum(10, 20);
    }
}
OutputSuccess
Important Notes

Parameter names are local to the method and only exist inside it.

You can have multiple parameters separated by commas.

Arguments must match the parameter types and order.

Summary

Parameters are placeholders in method definitions.

Arguments are actual values passed when calling methods.

Using parameters and arguments makes methods flexible and reusable.