C# Methods
A method in C# is a named block of code inside a class that runs only when something calls it, optionally returning a value. Methods let you group instructions under a name so you can reuse them instead of copying the same code again and again. You have already been using a method every time you wrote Console.WriteLine.
Creating a Method
A method is defined with a name followed by parentheses. The word void means the method does not return any value. By convention, method names in C# start with an uppercase letter. Code that belongs to the method goes inside the curly braces.
Defining a simple method
static void MyMethod()
{
Console.WriteLine("I just got executed!");
}Calling a Method
Defining a method does not run it. To actually run the code inside, you call the method by writing its name followed by parentheses and a semicolon. You can call the same method as many times as you like.
Calling a method more than once
static void MyMethod()
{
Console.WriteLine("I just got executed!");
}
static void Main()
{
MyMethod();
MyMethod();
MyMethod();
}
// Prints the message three timesWhy Use Methods?
- Reuse: write the code once and call it whenever you need it.
- Readability: a well-named method describes what a block of code does.
- Maintenance: fix a bug in one place instead of everywhere the code was copied.
A method that does a small job
static void Greet()
{
Console.WriteLine("Welcome to C#!");
}
static void Main()
{
Greet();
}Exercise: C# Methods
What does declaring a C# method's return type as void mean?