C# Methods
Methods are blocks of code that can be reused elsewhere in a C# application. Each application has at least one Main() method that acts as the starting point. Methods are used to avoid the repetition of code and make it maintainable and readable. Usually, a method has one or multiple dedicated purposes.
A function inside a class is called a method. As C# is an object-oriented programming language, all functions are declared inside classes, making them methods. Thus, methods and functions are synonymous.
Syntax
// Declare a public method without return type and no parameters:
public void PrintString()
{
Console.WriteLine("Hello, World!");
}
// Declare a private method which returns an object and takes no parameters:
private int ReturnNumber()
{
return 7;
}
// Declare a public method which returns an integer and takes an input parameter:
public int CalculateWithParameter(int x)
{
return ReturnNumber() - x;
}
Methods begin with a signature made of the following parts:
- An access level of
publicorprivate(privateis the default) - Optional modifiers (e.g.,
abstractandsealed) - The method return value (
string,int,object, etc.) orvoid - The method name (starting with a capital letter; usually a verb)
- Zero, one, or more (optional) parameters
Codebyte Example
In the following example, two methods are separate defined: Main() and GetSquare(). When the program is run, the Main() is executed first which, in turn, executes the GetSquare() method with an int parameter passed to it. The returned value is saved to a variable and printed to the console:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C# on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn Microsoft's popular C# programming language, used to make websites, mobile apps, video games, VR, and more.
- Beginner Friendly.15 hours