-
C# Methods
-
In C#, as applications grow, managing logic inside a single block of code becomes difficult and error-prone.
To write clean, scalable, and maintainable applications, developers use C# methods (functions) to organize logic into reusable blocks.
Methods are one of the core building blocks of C# programming. From simple operations like calculations to complex business logic, methods help structure your application in a professional and efficient way.
What are Methods in C#?
A method in C# is a block of code that performs a specific task and executes only when it is called.
Instead of repeating the same logic multiple times, a method allows you to define it once and reuse it wherever needed.
accessModifier returnType MethodName(parameters) { // method body }
Key Characteristics
- Encapsulates logic into reusable units
- Improves readability and maintainability
- Reduces duplication of code
- Makes debugging and testing easier
Understanding Method Syntax in C#
A method in C# is made up of multiple important components. Each part plays a specific role in defining how the method behaves.
public int AddNumbers(int a, int b) { return a + b; }
Parts of a Method
- Access Modifier → Defines who can access the method (
public,private, etc.) - Return Type → Specifies the type of value returned (e.g.,
int,string,void) - Method Name → Name of the method (should be meaningful, like
AddNumbers) - Parameters → Input values passed to the method
- Method Body → The block of code that performs the task
- Return Statement → Sends a value back to the caller (if return type is not
void)
Each of these components together defines how a method works and how it interacts with the rest of the application.
Why Methods Are Important
Consider a situation where the same logic is used multiple times.
int total1 = 100 + 200; int total2 = 300 + 400; int total3 = 500 + 600;
This leads to repetition and poor maintainability.
Using a method:
public int CalculateTotal(int a, int b) { return a + b; }
Calling it:
int total = CalculateTotal(100, 200);
This approach improves code reuse and readability.
Types of Methods in C#
1. No Parameters, No Return Value
public void Greet() { Console.WriteLine("Welcome!"); }
2. Parameters, No Return Value
public void PrintSum(int a, int b) { Console.WriteLine(a + b); }
3. Return Value, No Parameters
public int GetNumber() { return 10; }
4. Parameters and Return Value
public int Multiply(int x, int y) { return x * y; }
Calling a Method
A method must be invoked to execute its logic.
class Program { static void Main() { ShowMessage(); } public static void ShowMessage() { Console.WriteLine("Hello from method"); } }
Parameters and Return Types
Parameters allow methods to accept input values, making them flexible and reusable.
public int Square(int number) { return number * number; }
Calling:
int result = Square(5);
The
returnkeyword sends the computed value back to the caller.
Method Overloading
Method overloading allows multiple methods with the same name but different parameter types or counts.
public int Add(int a, int b) { return a + b; } public double Add(double a, double b) { return a + b; }
This improves flexibility and code readability.
Static vs Instance Methods
Static Method
A static method belongs to the class itself and can be called without creating an object.
class Calculator { public static int Add(int a, int b) { return a + b; } } class Program { static void Main() { // Calling static method without creating object int result = Calculator.Add(10, 20); Console.WriteLine(result); } }
Instance Method
An instance method requires an object of the class to be created before it can be called.
class Calculator { public int Add(int a, int b) { return a + b; } } class Program { static void Main() { // Creating object of Calculator Calculator calc = new Calculator(); // Calling instance method using object int result = calc.Add(10, 20); Console.WriteLine(result); } }
Example 1 : Order Calculation System
In an e-commerce application, calculating the final price is a common operation.
public double CalculateFinalPrice(double price, double tax) { double finalAmount = price + (price * tax); return finalAmount; }
Usage:
double total = CalculateFinalPrice(1000, 0.18);
This method ensures consistent calculation logic across the application.
Example 2 : Validation Logic
Validation is required in almost every application.
public bool IsValidEmail(string email) { if(email.Contains("@") && email.Contains(".com")) { return true; } return false; }
Usage:
bool isValid = IsValidEmail("test@gmail.com");
Keeping validation inside methods makes the code reusable and easier to maintain.
Common Mistakes
- Writing all logic inside
Main() - Creating overly large methods
- Using unclear method names
- Not using access specifiers properly
- Duplicating logic instead of reusing methods
Best Practices
- Keep methods short and focused
- Use meaningful names like
CalculateTotal,ValidateUser - Use appropriate access modifiers
- Avoid unnecessary parameters
- Follow single responsibility principle
Summary
C# methods form the foundation of writing clean, modular, and maintainable code.
They allow developers to organize logic into reusable blocks, reduce code duplication, and improve overall readability of applications. From simple operations to complex business logic, methods play a critical role in structuring real-world applications efficiently.
The next important step is to understand how data is passed into methods.
In the upcoming lesson, we will explore C# Method Parameters in detail, including ref, out, params, and optional parameters, and how they affect method behavior in real-world applications.