C# functions, also known as methods, are fundamental to object-oriented programming in C#. They encapsulate a set of instructions to perform a specific task, enhancing code reusability and maintainability. In this article, we'll explore various aspects of C# functions, including their syntax, types, and examples.
Understanding C# Functions
In C#, a function is declared using the void or a return type followed by the function name, parameters enclosed in parentheses, and the function body enclosed in curly braces. Here's a basic syntax:
```csharp returnType FunctionName(parameters) { // Function body } ```
Types of C# Functions
C# supports several types of functions, each serving a different purpose:

- Void Functions: These functions do not return any value. They are declared using the
voidkeyword. - Value-Returning Functions: These functions return a value of a specific data type. The return type is specified before the function name.
- Overloaded Functions: Functions with the same name but different parameters. C# allows multiple functions with the same name but different parameters in the same scope.
- Recursive Functions: Functions that call themselves during their execution.
Void Functions Example
```csharp public void SayHello(string name) { Console.WriteLine($"Hello, {name}!"); } ```Value-Returning Functions Example
```csharp public int AddNumbers(int a, int b) { return a + b; } ```Overloaded Functions Example
```csharp public int AddNumbers(int a, int b) { return a + b; } public double AddNumbers(double a, double b) { return a + b; } ```Recursive Functions Example
```csharp public int Factorial(int number) { if (number == 0 || number == 1) return 1; else return number * Factorial(number - 1); } ```Function Parameters
Functions can accept input parameters to perform operations. Parameters are declared inside the parentheses following the function name. Here's how you can declare parameters:
```csharp returnType FunctionName(parameterType1 parameterName1, parameterType2 parameterName2, ...) { // Function body } ```
Lambdas and Anonymous Methods
C# also supports lambda expressions and anonymous methods, which are compact ways to define functions. Lambdas are used to define delegates and anonymous methods are used to define methods without a name. Here's an example of each:
```csharp
// Lambda expression
Func Extension methods allow you to add new methods to existing types without creating a new derived type. They are defined using the Extension Methods
this keyword. Here's an example:

```csharp public static class StringExtensions { public static bool IsNullOrWhiteSpace(this string str) { return string.IsNullOrWhiteSpace(str); } } ```
With this extension method, you can now call IsNullOrWhiteSpace on a string like this:
```csharp string str = " "; bool result = str.IsNullOrWhiteSpace(); ```





















