Return Types
A return type says what kind of answer a method gives back, like a vending machine promising a drink or a snack. Some methods return nothing at all, which is called void.
In this page:
Syntax
static ReturnType MethodName(type parameter)
{
return value;
}
ReturnType result = MethodName(argument);
Return Types
A method's return type declares what kind of value it hands back to its caller with the return keyword. A method that returns nothing uses void. Every code path in a non-void method must return a value, or the compiler raises an error.
Warning:
Leaving out a
return on some code path of a non-void method is a compile error, not a runtime one.Example: Return Types
using System;
class Program
{
static int Square(int n)
{
return n * n;
}
static void Main(string[] args)
{
int result = Square(6);
Console.WriteLine(result);
}
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Returning a value from a
voidmethod, which is a compile error. - Forgetting that all code paths must return a value in a non-void method.
- Returning
nullfor a value type such asintwithout usingint?.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: