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#.
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();
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}");
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}");
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();
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!
One of the common questions among Docker users is whether Docker containers consume disk space.…
Sorting data is a common operation in programming, allowing you to organize information in a…
Splitting a string into an array of substrings is a common operation in C# programming,…
Starting the Docker daemon is the first step towards managing Docker containers and images on…
Serializing an object to JSON (JavaScript Object Notation) format is a common task in C#…
When running Docker containers, you may encounter scenarios where containers need to access resources outside…