C# Language Methods Return Types

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

A method can return either nothing (void), or a value of a specified type:

// If you don't want to return a value, use void as return type.
static void ReturnsNothing() { 
    Console.WriteLine("Returns nothing");
}

// If you want to return a value, you need to specify its type.
static string ReturnsHelloWorld() {
    return "Hello World";
}

If your method specifies a return value, the method must return a value. You do this using the return statement. Once a return statement has been reached, it returns the specified value and any code after it will not be run anymore (exceptions are finally blocks, which will still be executed before the method returns).

If your method returns nothing (void), you can still use the return statement without a value if you want to return from the method immediately. At the end of such a method, a return statement would be unnecessary though.

Examples of valid return statements:

return; 
return 0; 
return x * 2;
return Console.ReadLine();

Throwing an exception can end method execution without returning a value. Also, there are iterator blocks, where return values are generated by using the yield keyword, but those are special cases that will not be explained at this point.



Got any C# Language Question?