C# Methods for Beginners
A method is a named block of code that performs a task. Methods make programs easier to read, test, reuse, and change because related logic can be given a clear name and called from different places.
A simple method
static void SayHello()
{
Console.WriteLine("Hello!");
}
SayHello();
This method has no parameters and returns no value. The void keyword means the caller does not receive a result from the method.
Parameters
static void Greet(string name)
{
Console.WriteLine($"Hello, {name}!");
}
Greet("Ravi");
Parameters allow a method to work with data supplied by the caller. The parameter has a declared type, and the argument supplied at the call site must be compatible with that type.
Return values
static int Add(int a, int b)
{
return a + b;
}
int result = Add(10, 20);
The method returns an int, so the caller can store the result in an integer variable. Returning a value is useful when a method calculates something that another part of the program needs.
Expression-bodied methods
static int Square(int number) => number * number;
For a small method whose implementation is a single expression, C# provides an expression-bodied syntax. Use it when the shorter form remains easy to understand.
Optional parameters
static void PrintMessage(string message = "Hello")
{
Console.WriteLine(message);
}
PrintMessage();
PrintMessage("Welcome to C#");
An optional parameter provides a default value when the caller does not supply an argument.
Method overloading
static int Add(int a, int b) => a + b;
static double Add(double a, double b) => a + b;
Methods can share a name when their parameter lists are different. This is called overloading and can make an API easier to use when the same operation naturally applies to different types.
Common beginner mistakes
- Declaring a return type but forgetting to return a value on every required path.
- Calling a method with arguments whose types do not match its parameters.
- Putting unrelated responsibilities into one very large method instead of splitting the work into smaller operations.
How to design a useful method
Start with a method name that describes one clear responsibility. Keep its parameters focused on the information it actually needs, and return a useful value when the caller needs a result. Small methods are easier to test and reuse as an application grows.
Continue with the C# Tutorials pillar when you are ready for deeper topics.
đŦ Comments
Sign in with Google to publish immediately, or comment anonymously and wait for approval.
Comments will appear here when available.