Part 5: Functions and Methods in C#
Functions and methods are essential building blocks in programming that allow you to group reusable blocks of code. In C#, these constructs enable modular and maintainable code design. In this lesson, we will cover the concept of methods, how to create and use them, and how to work with parameters, return values, and method overloading.
1. What is a Method?
A method in C# is a block of code that performs a specific task. It can take input (parameters), perform operations, and optionally return a result. Methods help to make code more organised and reusable.
Example of a Simple Method
public void Greet() { Console.WriteLine("Hello, Codú!"); }
This method, named Greet
, outputs a greeting message when called.
2. Creating and Using Methods in C#
Defining a Method
To define a method in C#, you need to specify:
- Access Modifier: Defines the visibility (e.g.,
public
,private
). - Return Type: Specifies the type of data the method returns (
void
if it doesn't return anything). - Method Name: A unique identifier for the method.
- Parameters: Optional inputs to the method (inside parentheses).
Example: Method with Parameters
public int Add(int a, int b) { return a + b; }
This method, Add
, takes two integers as parameters and returns their sum.
Calling a Method
To use a method, simply call it by its name and pass the required arguments (if any):
int result = Add(2, 8); Console.WriteLine($"The sum is {result}");
3. Parameters and Return Values
Parameters
Parameters are placeholders in the method definition that accept values when the method is called.
Example: Passing Parameters
public void PrintMessage(string message) { Console.WriteLine(message); }
PrintMessage("Welcome to Codú!");
Return Values
Methods can return a value using the return
keyword.
Example: Returning a Value
public double Multiply(double x, double y) { return x * y; }
double product = Multiply(4.5, 2.3); Console.WriteLine($"The product is {product}");
4. Method Overloading
Method overloading allows you to define multiple methods with the same name but different parameter lists. This is useful when you need to perform similar tasks with different input types or counts.
Example: Overloaded Methods
public void Display(string message) { Console.WriteLine(message); } public void Display(string message, int count) { for (int i = 0; i < count; i++) { Console.WriteLine(message); } }
Display("Hello Codú"); Display("Repeat", 3);
5. Practical Example: Creating Methods
Let’s create a simple program that calculates the area of a rectangle using a method.
public double CalculateArea(double width, double height) { return width * height; } // Calling the method double area = CalculateArea(8.0, 4.5); Console.WriteLine($"The area of the rectangle is {area}");
This method takes two parameters (width
and height
) and returns their product as the area of the rectangle.
6. Real-World Use Cases
File Operations Example
Here’s a method to create a file and write text into it:
public void CreateFile(string fileName, string content) { File.WriteAllText(fileName, content); Console.WriteLine($"File {fileName} created successfully."); } // Usage CreateFile("example.txt", "Hello, Codú!");
User Input Example
A method to read user input and return it:
public string GetUserInput() { Console.Write("Enter your name: "); return Console.ReadLine(); } // Usage string name = GetUserInput(); Console.WriteLine($"Hello, {name}!");
7. Handling Edge Cases
Null Checks and Validation
When writing methods, it’s important to validate inputs to avoid runtime errors. For example:
public void PrintUppercase(string text) { if (string.IsNullOrEmpty(text)) { Console.WriteLine("Invalid input: text cannot be null or empty."); return; } Console.WriteLine(text.ToUpper()); } // Usage PrintUppercase(null);
8. Advanced Topics
Static Methods
Static methods belong to the class rather than an instance of the class. They are called directly using the class name.
public static void PrintDate() { Console.WriteLine(DateTime.Now); } // Usage ClassName.PrintDate();
Recursive Methods
A recursive method is a method that calls itself. For example, calculating the factorial of a number:
public int Factorial(int n) { if (n == 1) return 1; return n * Factorial(n - 1); } // Usage int result = Factorial(5); Console.WriteLine($"Factorial: {result}");