A method in C# is a function defined inside a class that defines what an object can do.
This page covers Method in C#. For a language-agnostic introduction, see Method.
Defining a Method#
A C# method has an access modifier, a return type, a name, and a body.
public void Greet()
{
Console.WriteLine("Hello!");
}public— the access modifier;publicmeans the method can be called from anywherevoid— the return type;voidmeans the method returns nothingGreet— the method name; use PascalCase by convention()— the parameter list; empty here, but arguments go inside these parentheses
Return Types#
If a method produces a value, declare the return type instead of void and use return to send it back.
public int Add(int a, int b)
{
return a + b;
}Parameters#
Parameters are declared inside the parentheses as type name pairs, separated by commas.
public void Greet(string name)
{
Console.WriteLine($"Hello, {name}!");
}Calling a Method#
Call a method on an object using dot notation.
Player player = new Player();
player.Greet("Alice");Common Mistakes#
Using the wrong return type
If a method is declared as void but contains a return value; statement, it’s a compile error. If it’s declared with a return type but doesn’t return anything, that’s also a compile error. The declared return type and the actual return must match.
PascalCase vs camelCase
C# convention is PascalCase for method names: Greet, Play, GetScore. Using camelCase (greet, play) won’t break the code, but it goes against the style the C# community expects.
Calling the method without an object
Non-static methods must be called on an instance: player.Greet(), not Player.Greet(). Calling a non-static method on the class itself is a compile error.
Forgetting the return statement
If a method has a non-void return type, every code path must end with a return statement. Forgetting it in one branch of an if/else is a compile error.
Resources#
- Methods (C# programming guide) (external link) — Microsoft Learn
- Method (computer programming) (external link) — Wikipedia