C# Programming Fundamentals
Methods and Functions
Building with Methods
So far, you've written code that runs from top to bottom. As your programs grow, you'll find yourself writing the same lines of code over and over. Methods, also called functions, are how you solve this. They are reusable blocks of code that perform a specific task.
Think of a method as a recipe. Instead of rewriting the steps to make a sauce every time you need it, you just refer to the "Sauce Recipe." In C#, you define the recipe once and then "call" it whenever you need it.
A method has two parts: the definition (the recipe itself) and the call (using the recipe). Let's define a simple method that prints a greeting.
// Method Definition
void SayHello()
{
Console.WriteLine("Hello from a method!");
}
// Method Call
SayHello(); // This line executes the code inside the method.
Here, void is the return type. It means this method doesn't send any data back after it runs. SayHello is the method's name, and the parentheses () are for parameters, which we'll cover next. The code to be executed is placed inside the curly braces {}.
Passing Information
Methods become truly powerful when you can pass information into them and get information out. You pass data into a method using parameters, and you get data out using a return value.
Parameters are like the ingredients for your recipe. A return value is the finished dish.
Let's modify our SayHello method to accept a name. The string name inside the parentheses is a parameter. It's a variable that exists only within this method.
void GreetByName(string name)
{
Console.WriteLine($"Hello, {name}!");
}
// Now we provide a value (an "argument") when we call it.
GreetByName("Alice");
GreetByName("Bob");
What if you want a method to perform a calculation and give you the result? You change the void return type to the data type you want back. The return keyword sends the value back to where the method was called.
int Add(int number1, int number2)
{
int sum = number1 + number2;
return sum; // Send the result back
}
// Call the method and store its return value in a variable.
int result = Add(5, 3);
Console.WriteLine(result); // Outputs: 8
Same Name, Different Job
Sometimes you need a method that does the same basic thing but with different types or numbers of inputs. For example, you might want to add two integers, or you might want to add two decimal numbers. This is where method overloading comes in.
Method overloading lets you define two or more methods with the same name, as long as their parameter lists (or "signatures") are different. The compiler knows which one to call based on the arguments you provide.
The difference in the method signature can be the number of parameters or the data type of the parameters.
// Overload 1: Adds two integers
int Add(int a, int b)
{
return a + b;
}
// Overload 2: Adds two doubles
double Add(double a, double b)
{
return a + b;
}
// Overload 3: Adds three integers
int Add(int a, int b, int c)
{
return a + b + c;
}
// The compiler chooses the right method:
Console.WriteLine(Add(2, 3)); // Calls Overload 1
Console.WriteLine(Add(2.5, 3.1)); // Calls Overload 2
Console.WriteLine(Add(2, 3, 5)); // Calls Overload 3
Where Variables Live
An important concept when working with methods is scope. A variable's scope defines where in your program it can be accessed. In C#, scope is generally determined by curly braces {}.
A variable declared inside a method is a local variable. It only exists from the point of its declaration until the method's closing curly brace
}. Its lifetime is tied to the execution of that method.
Think of it like a conversation in a room. The words spoken in that room are only heard by the people inside. Once you leave the room, the conversation is over. Similarly, once a method finishes running, its local variables disappear.
void MyMethod()
{
// 'message' is local to MyMethod
string message = "This exists only inside MyMethod.";
Console.WriteLine(message);
} // 'message' is destroyed here
void AnotherMethod()
{
// This would cause an error, because 'message' doesn't exist here.
// Console.WriteLine(message);
}
MyMethod();
This scoping rule helps prevent accidental conflicts. You can have a variable named result in two different methods, and they won't interfere with each other because they live in separate scopes.
Let's test your understanding of these concepts.
What is the primary purpose of using methods (or functions) in programming?
In the following C# method definition, what is the 'return type'?
public string GetGreeting(string name)
{
return "Hello, " + name;
}
Using methods to organize your code is a fundamental skill that leads to cleaner, more efficient, and easier-to-maintain programs.