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!
Encapsulation and abstraction are two pillars of object-oriented programming (OOP) that play a vital role…
Polymorphism is a fundamental concept in object-oriented programming (OOP) that allows objects to take on…
Inheritance is a cornerstone of object-oriented programming (OOP) and one of its most powerful features.…
In the world of C# and object-oriented programming (OOP), classes and objects form the backbone…
In modern C# programming, working with data collections is a common task. Understanding how to…
Exception handling is a critical part of writing robust and maintainable C# applications. It allows…