Declare A Void Function Without Return Value In C#
Code snippet for how to Declare A Void Function Without Return Value In C# with sample and detail explanation
In C#, a void function is defined as one that doesn’t return any data. You call these methods to perform an action rather than to compute and return a specific value.
Code snippet for Declaring a Void Function Without Return Value
Here is a simple code snippet illustrating how to declare a void function in C#.
public class Program {
public static void Main(string[] args) {
DisplayMessage();
}
public static void DisplayMessage() {
System.Console.WriteLine("This is a void function.");
}
}
Code Explanation for Declaring a Void Function Without Return Value
Let’s do a breakdown of the code snippet for better understanding.
The code declares a static class named ‘Program’ that includes two methods:
- The ‘Main’ method - this is the entry point to the program.
- The ‘DisplayMessage’ method - this is the void function that we are focusing on.
The keyword ‘void’ explicitly tells the compiler that the function ‘DisplayMessage’ does not return any value.
Inside ‘DisplayMessage’ function, we have only one statement that prints out the text “This is a void function.” on the console screen.
Back in the ‘Main’ method, we call the ‘DisplayMessage’ function using its name followed by brackets. Since ‘DisplayMessage’ is a void function, we do not expect it to return any value. It will merely execute the code written in its body, which in this case is to print out a console message.
In conclusion, the use of void functions in C# is very common and useful for performing actions where you don’t need to return any specific value back to the caller.