Welcome to Lesson 10! In this lesson, we’ll explore functions, also known as methods in C#. Functions are fundamental building blocks in programming that allow you to organize, reuse, and manage your code efficiently. We’ll cover how to define, call, and work with functions in C#.
1. What is a Function/Method?
A function (or method) is a reusable block of code that performs a specific task. Functions help you avoid code duplication and make your program easier to maintain and understand. In C#, functions are referred to as methods when they are part of a class.
2. Defining a Method
To define a method, you specify its return type, name, parameters (if any), and the body of the method. The return type indicates what type of value the method will return. If the method doesn’t return a value, the return type is void
.
Syntax:
returnType MethodName(parameters)
{
// Method body
return returnValue; // Optional, if returnType is not void
}
Example:
int Add(int a, int b)
{
return a + b;
}
Explanation:
int
is the return type.Add
is the method name.(int a, int b)
are the parameters.return a + b;
returns the sum ofa
andb
.
3. Calling a Method
To use a method, you call it by its name and provide the necessary arguments.
Example:
int result = Add(5, 3);
Console.WriteLine(result); // Output: 8
Explanation:
- The
Add
method is called with arguments5
and3
, and the result is stored inresult
.
4. Methods with No Return Value
If a method does not return a value, use void
as the return type.
Example:
void PrintMessage(string message)
{
Console.WriteLine(message);
}
Calling the Method:
PrintMessage("Hello, world!"); // Output: Hello, world!
Explanation:
PrintMessage
prints the provided message to the console and does not return a value.
5. Method Overloading
Method overloading allows you to define multiple methods with the same name but different parameters. C# distinguishes overloaded methods by their parameter lists.
Example:
int Multiply(int a, int b)
{
return a * b;
}
double Multiply(double a, double b)
{
return a * b;
}
Explanation:
- Two
Multiply
methods are defined: one for integers and one for doubles. C# determines which method to call based on the argument types.
6. Optional Parameters
You can specify default values for parameters, making them optional when calling the method.
Example:
void Greet(string name, string greeting = "Hello")
{
Console.WriteLine($"{greeting}, {name}!");
}
Calling the Method:
Greet("Alice"); // Output: Hello, Alice!
Greet("Bob", "Goodbye"); // Output: Goodbye, Bob!
Explanation:
- The
greeting
parameter has a default value of “Hello”. If no value is provided, the default is used.
7. Return Statements
The return
statement is used to return a value from a method. If the return type is void
, you use return
to exit the method early.
Example:
int Square(int number)
{
return number * number;
}
void PrintSquare(int number)
{
int result = Square(number);
Console.WriteLine(result);
}
Explanation:
- The
Square
method returns the square of a number. - The
PrintSquare
method callsSquare
and prints the result.
8. Passing Parameters by Reference
Parameters can be passed by reference using the ref
or out
keywords, allowing methods to modify the original variables.
Example Using ref
:
void Increment(ref int number)
{
number++;
}
int value = 5;
Increment(ref value);
Console.WriteLine(value); // Output: 6
Explanation:
- The
Increment
method modifies thevalue
variable directly because it is passed by reference usingref
.
9. Methods with out
Parameters
The out
keyword allows a method to return multiple values by modifying variables passed as arguments.
Example:
void Divide(int dividend, int divisor, out int quotient, out int remainder)
{
quotient = dividend / divisor;
remainder = dividend % divisor;
}
int q, r;
Divide(10, 3, out q, out r);
Console.WriteLine($"Quotient: {q}, Remainder: {r}"); // Output: Quotient: 3, Remainder: 1
Explanation:
- The
Divide
method calculates both the quotient and remainder, which are returned usingout
parameters.
10. Example: Calculating Factorial
Let’s create a method to calculate the factorial of a number using recursion.
Example:
int Factorial(int n)
{
if (n <= 1)
return 1;
else
return n * Factorial(n - 1);
}
Console.WriteLine(Factorial(5)); // Output: 120
Explanation:
- The
Factorial
method calls itself recursively to compute the factorial of a number.
Summary
In this lesson, you learned about functions (methods) in C#, including how to define, call, and work with them. We covered different aspects such as method overloading, optional parameters, passing parameters by reference, and returning multiple values. Methods are essential for writing clean, reusable, and organized code.
Happy coding!
0 Comments