C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Here: We declare and use a static void method (Example1). The control flow jumps to this method when you invoke it, but there is no result.
Note: It is a compile-time error to assign to the Example method invocation. No variable can be assigned to void.
Next: We use an instance void method. To declare an instance method, omit the static modifier. Methods are by default considered instance.
Parameters: Void methods receive parameters like all methods—they use a simple "return" statement that is followed by a semicolon.
ReturnC# program that declares void type methods
using System;
class Program
{
static void Example1()
{
Console.WriteLine("Static void method");
}
void Example2()
{
Console.WriteLine("Instance void method");
return; // Optional
}
static void Main()
{
//
// Invoke a static void method.
//
Example1();
//
// Invoke an instance void method.
//
Program program = new Program();
program.Example2();
//
// This statement doesn't compile.
//
// int x = Example1();
}
}
Output
Static void method
Instance void method
Ret: The void method must have no elements on the evaluation stack when the "ret" instruction is reached.
Book: The book Expert .NET IL 2.0 Assembler by Serge Lidin provides an excellent description of this requirement.
Intermediate language for void method: IL
.method private hidebysig static void Example1() cil managed
{
.maxstack 8
L_0000: ldstr "Static void method"
L_0005: call void [mscorlib]System.Console::WriteLine(string)
L_000a: ret
}
Info: Because void primarily impacts the compile-time processing of a program, no errors will be caused by void specifically at runtime.
Instead: The void type will instead force compile-time errors. These are useful—they help us improve programs.
C# program that causes compile-time error
class Program
{
static void VoidMethod()
{
}
static void Main()
{
int result = VoidMethod();
}
}
Output
Error 1:
Cannot implicitly convert type void to int.
Important: You cannot overload methods based on their return types such as void alone in the C# language.
OverloadNote: The IL supports overloading on return type. It identifies methods based on a triad: return type, identifier, and parameter list.