Computer Screen

Unraveling Functions and Methods in C#

Functions and methods are fundamental to structuring code in C#. They encapsulate blocks of code that perform specific tasks and can be called upon when needed. In this post, we’ll explore the different forms of functions and methods in C#.

Function Declaration and Expression:

A function in C# can be declared using the void keyword for methods that don’t return a value. Here’s an example:

void SayHello()
{
    Console.WriteLine("Hello, World!");
}

// Calling the function
SayHello();

Parameters and Return Values:

Functions can take parameters and return values, allowing for more flexibility. Here’s an example of a function that calculates the sum of two numbers:

int Add(int a, int b)
{
    return a + b;
}

// Calling the function with arguments
int result = Add(3, 7);
Console.WriteLine($"Sum: {result}");

Arrow Functions (Lambda Expressions):

C# supports arrow functions, also known as lambda expressions, for concise function expressions. Here’s an example:

Func<int, int, int> Multiply = (x, y) => x * y;

// Calling the lambda function
int product = Multiply(4, 5);
Console.WriteLine($"Product: {product}");

Scope and Closures:

Understanding the scope of variables and closures is crucial when working with functions. Here’s a brief example:

int globalVariable = 10;

void DisplayGlobal()
{
    Console.WriteLine($"Global Variable: {globalVariable}");
}

// Calling the function
DisplayGlobal();

Conclusion:

Functions and methods form the building blocks of C# programs. They promote code reusability and maintainability. In the next post, we’ll explore the concise syntax of arrow functions in C#. Feel free to review the content, and if you have any feedback or specific points you’d like to elaborate on, let me know. Once you’re satisfied with this post, we can move on to the next topic!

Leave a Reply

Your email address will not be published. Required fields are marked *


Categories


Tag Cloud

.net algorithms angular api Array arrays async asynchronous basic-concepts big o blazor c# classes code components containers control-structures csharp data structures data types dictionaries docker dom dotnet framework functions git guide Inheritance javascript json leetcode linq lists loops methods MVC npm object oriented programming oop operators sorted try catch typescript web framework