π§ C# Methods β Mastering the Basics of Reusable Code
π§² Introduction β Why Learn Methods in C#?
Methods are the building blocks of any C# application. They allow you to organize logic, reuse code, and maintain cleaner structure in programs. Whether youβre building a console app, a web API, or a Unity game, understanding how to define and call methods is essential.
π― In this guide, youβll learn:
- What methods are and how they work
- How to declare and call a method
- Return types and void methods
- Scope and structure of methods
- Best practices with examples
π Core Concept β What is a Method in C#?
A method is a named block of code designed to perform a specific task. It can be invoked whenever needed and may return a value or perform an action.
π£ Method Syntax:
return_type MethodName(parameters)
{
// Code block
return value; // if not void
}
π Example β Method Without Return (void):
void SayHello()
{
Console.WriteLine("Hello from method!");
}
π Example β Method With Return:
int Add(int a, int b)
{
return a + b;
}
π» Code Example β Method Calling
void GreetUser(string name)
{
Console.WriteLine($"Welcome, {name}!");
}
GreetUser("Alice");
π₯ Output:
Welcome, Alice!
π§΅ Explanation:
GreetUser
is defined with a parametername
.- The method is called and passed
"Alice"
as an argument.
π§ Method with Return Value
double Square(double num)
{
return num * num;
}
double result = Square(4.5);
Console.WriteLine($"Result: {result}");
π₯ Output:
Result: 20.25
π Use Case: Encapsulate logic for reuse and testing.
π Methods with Multiple Parameters
void DisplayInfo(string name, int age)
{
Console.WriteLine($"Name: {name}, Age: {age}");
}
DisplayInfo("Bob", 30);
π Use Case: Pass dynamic values into a method for processing.
π Void vs Non-Void Methods
Feature | void Method | Method with Return |
---|---|---|
Purpose | Performs an action | Calculates and returns a value |
Return Keyword | Not required | Required (return value; ) |
Use Case | Printing, logging, UI updates | Math calculations, data processing |
π‘ Best Practices & Tips
π‘ Tip: Keep methods short and focused on a single task.
β οΈ Pitfall: Avoid duplicating logic; use methods to encapsulate repeatable code.
π Best Practice: Use meaningful method names that clearly describe the action (CalculateTax()
, PrintInvoice()
).
π οΈ Real-World Use Cases
- π Input validation functions
- π’ Mathematical operations
- π§Ύ Invoice generation
- π§ͺ Reusable utility functions (e.g., formatting, logging)
- π§ Business logic layers in APIs
π Summary β Recap & Next Steps
π§΅ Key Takeaways:
- Methods improve code organization, reuse, and testing.
- C# methods can return values (
int
,string
, etc.) or bevoid
. - Parameterized methods allow dynamic input during execution.
βοΈ Real-world relevance: Critical for modular programming across desktop, web, and mobile applications in C#.
β FAQ Section
β What is the difference between a function and a method in C#?
β
In C#, the term method is used (not function), and it’s a member of a class.
β Can I declare a method inside another method in C#?
β
No. Methods must be declared at the class levelβnot inside other methods.
β How many parameters can a method accept?
β
As many as needed, but readability is important. Consider using objects for too many parameters.
β Can I overload methods in C#?
β
Yes! You can define multiple methods with the same name but different parameters (see: Method Overloading).
β Are all methods public in C#?
β
No. By default, methods are private
in classes unless explicitly marked public
, protected
, etc.
Share Now :