Declare A Simple Function In C#
Code snippet for how to Declare A Simple Function In C# with sample and detail explanation
In this article, we’ll discuss how to declare a simple function in C#. This is a basic concept, but crucial to mastering any programming language including C#.
Simple Function Declaration In C#
Before we delve into the details, let’s look at an example of a simple function in C#.
public static void GreetUser(string userName)
{
Console.WriteLine("Hello, " + userName);
}
Code Explanation for Simple Function Declaration In C#
Here is a step-by-step explanation of the above function.
-
Function Declaration: The function begins with the public static void keywords. ‘Public’ is an access modifier that determines the visibility of the method. In this case, the method can be accessed from any class. ‘Static’ means that the method belongs to the class itself, and not an instance of the class. ‘Void’ indicates that this function will not return any value.
-
Function Name: The function’s name is ‘GreetUser’. The function name should ideally describe what the function does. In this case, it indicates that this function is used to greet the user.
-
Parameters: The parameter is a string type variable named ‘userName’. The function is declared in such a way that it expects a string type value whenever it is called. This value is used within the function to personalize the greeting.
-
Function Body: The function body starts and ends with a pair of curly braces {}. Inside the function body, we have a single line of code which uses the Console.WriteLine() function to display a string to the console. In this case, it will display ‘Hello’ followed by the user’s name passed through the function parameter.
-
Calling the Function: To call the function elsewhere in code, you’d use:
GreetUser("John");
. “John” in this case is an argument that will be used as ‘userName’ string inside the function.
This is a simple example, but accurately illustrates how to declare a function in C#. Creating customized functions is a valuable tool in creating clean, readable, and reusable code.