Search⌘ K
AI Features

Parameters Passing and Methods Overloading

Explore how to define and pass parameters to methods in C#, enabling customizable method behavior. Understand method overloading to create multiple methods with the same name differentiated by parameter signatures. This lesson helps you write reusable and flexible code by mastering these foundational object-oriented programming concepts.

In C#, methods are essential for defining reusable blocks of code. They can also accept parameters, allowing us to customize their behavior. We’ll explore method overloading, which allows us to define multiple methods with the same name but different parameter signatures.

Defining and passing parameters to methods

Methods can have parameters passed to them to change their behavior. Parameters are defined like variable declarations but inside the method’s parentheses, as we saw earlier with constructors. Let’s see more examples:

Step 1: In Person.cs, add statements to define two methods, the first without parameters and the second with one parameter, as shown in the following code:

C#
public string SayHello()
{
return $"{Name} says 'Hello!'";
}
public string SayHelloTo(string name)
{
return $"{Name} says 'Hello, {name}!'";
}
...