Mark As Completed Discussion

Functions

Functions are an essential part of any programming language, including C#. They allow you to break down your code into smaller, reusable blocks that perform a specific task.

In C#, you can define a function using the void keyword followed by the function name and parentheses. If the function takes parameters, you can specify them within the parentheses. Here's an example:

TEXT/X-CSHARP
1void PrintMessage(string message)
2{
3    Console.WriteLine(message);
4}

In the above example, we defined a function named PrintMessage that takes a string parameter named message. The function body is enclosed within curly braces {}.

Once a function is defined, you can call it by its name followed by parentheses. If the function takes parameters, you can pass the values within the parentheses. Here's how you can call the PrintMessage function:

TEXT/X-CSHARP
1PrintMessage("Hello, world!");

The output of the above code will be:

SNIPPET
1Hello, world!

Functions can also have a return type instead of void. A return type specifies the type of value that the function will return after performing its task. Here's an example:

TEXT/X-CSHARP
1int Add(int a, int b)
2{
3    return a + b;
4}

In the above example, we defined a function named Add that takes two int parameters, a and b. The function body adds the values of a and b and returns the result.

You can call the Add function and store its return value in a variable, like this:

TEXT/X-CSHARP
1int result = Add(3, 4);
2Console.WriteLine("The result is: " + result);

The output of the above code will be:

SNIPPET
1The result is: 7

Functions are powerful tools that allow you to organize your code, make it more readable, and reuse it. They play a crucial role in modular programming and are widely used in various applications, including microservices development in C#. Understanding functions is essential for building efficient and maintainable code.

C#
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment