Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

Method Parameters and Return Values in C#

Introduction

In C#, methods are used to perform specific tasks. They can take inputs, known as parameters, and can return a value after execution. Understanding how to define and use method parameters and return values is crucial for writing effective and reusable code.

Method Parameters

Method parameters allow you to pass data into methods. Parameters can be of any data type, and you can have multiple parameters in a single method.

Here is the syntax for defining a method with parameters:

public void MethodName(parameterType parameterName) {
    // Method body
}
                

Example:

public void Greet(string name) {
    Console.WriteLine("Hello, " + name);
}
                

In this example, the Greet method takes a single parameter of type string and prints a greeting message.

Calling a Method with Parameters

When calling a method with parameters, you need to provide the arguments corresponding to the parameters defined in the method signature.

Example:

Greet("Alice");
                

This will output:

Hello, Alice

Return Values

Methods can return a value to the caller. The return type is specified in the method signature. If a method does not return a value, the return type is void.

Here is the syntax for defining a method with a return value:

public returnType MethodName(parameterType parameterName) {
    // Method body
    return value;
}
                

Example:

public int Add(int a, int b) {
    return a + b;
}
                

In this example, the Add method takes two integer parameters and returns their sum as an integer.

Calling a Method with a Return Value

When calling a method with a return value, you typically store the returned value in a variable or use it directly.

Example:

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

This will output:

8

Multiple Parameters and Return Values

Methods can have multiple parameters and a single return value. You can mix and match different data types for parameters.

Example:

public double CalculateArea(double width, double height) {
    return width * height;
}
                

Calling this method:

double area = CalculateArea(5.0, 3.5);
Console.WriteLine(area);
                

This will output:

17.5

Conclusion

Understanding method parameters and return values is essential for writing modular and reusable code in C#. By passing parameters to methods, you can provide the necessary data for execution. By returning values, methods can provide meaningful results to the caller. Practice defining and calling methods with various parameters and return types to get a solid grasp of these concepts.