A Method in C# is a block of code that performs a specific task. Think of it like a machine:
The basic syntax of a method:
Anatomy (parts) of a method:
✅ Use clear names + small, focused methods to make your code easy to read, test, and reuse.
Methods are not just about writing code — they make your programs cleaner, faster, and easier to maintain. Here’s why every developer should use methods effectively:
Write the logic once and call it many times wherever needed. This avoids duplicate code and saves development time.
Breaking big logic into small, clearly named methods makes your code easy to understand for you and for other team members.
Small methods can be unit tested independently, ensuring your application is bug-free and works as expected.
If a bug appears, you fix it in one place and the benefit reflects everywhere the method is used — reducing future issues.
Methods define clear inputs and outputs, so multiple developers can work together without confusion.
Well-structured methods optimize execution flow and help identify performance bottlenecks easily during testing.
✅ Using methods wisely makes your application modular, reusable, and professional.
Methods in C# can be classified based on two main factors:
Based on these, there are four common combinations of methods:
void SayHello() { Console.WriteLine("Hello!"); }
void Greet(string name) { Console.WriteLine("Hello " + name); }
int GetNumber() { return 10; }
int Add(int a, int b) { return a + b; }
➡️ These methods perform a simple action without any inputs or results. Perfect for tasks like showing messages or logs.
Example use: Displaying a welcome message when the program starts.
➡️ These methods take input data but do not return anything. The action is performed based on provided parameters.
Example use: Printing a user's name or sending data to a printer.
➡️ These methods return a value but do not require any input. Useful for giving constant values or random numbers.
Example use: Generating a random OTP or retrieving system date.
➡️ These methods take input data, process it, and return the result. They are most commonly used in real applications.
Example use: Performing calculations like sum, average, or discount.
✅ Understanding these combinations with examples helps you write clean, reusable, and testable C# programs.
Methods in C# can be classified based on parameters (inputs) and return values (outputs). This section covers when and how to use them effectively.
✔️ Use when: The work doesn’t need outside data, e.g., simple actions or one-time setup.
⚠️ Trade-off: Less flexible because you can’t pass dynamic data.
✔️ Use when: The work depends on external input.
✅ Benefits: Flexible, testable, reusable.
Rule of thumb: Prefer passing data via parameters instead of reading global state.
✔️ Pros: Simple to implement.
⚠️ Cons: No result to chain or test easily if it only does side effects.
✔️ Pros: Composable, testable (pure functions).
⚠️ Cons: Harder to reason about if side effects are mixed in.
static void SeedDefaults() { // Insert default rows into the database Console.WriteLine("Default rows inserted successfully."); }
Use For: Initialization tasks, notifications, one-time setups.
Example: Setting up default admin users, sending startup logs.
Watch For: Hidden dependencies like database or global variables.
static void EmailInvoice(int invoiceId, string email) { // Send invoice to the given email Console.WriteLine($"Invoice {invoiceId} sent to {email}"); }
Use For: Commands like sending emails, writing logs, saving records.
Example: Send SMS notification after ticket booking.
Watch For: Failures — consider returning status or throwing exceptions.
static DateTime GetServerTime() { return DateTime.UtcNow; }
Use For: Read-only queries like fetching system information.
Example: Get current server time for logging or display purposes.
Watch For: Hidden states or time dependencies — hard to test deterministically.
static decimal CalculateGst(decimal amount, decimal rate) { return amount * rate; }
Use For: Pure calculations, financial formulas, data processing.
Example: Calculate discount price, tax amount, or loan EMI.
Watch For: Input validation for nulls or invalid ranges.
Methods are building blocks of clean and maintainable code. They help us write reusable, testable, and readable programs. Below is a deeper look at the advantages and disadvantages of using methods in real-world projects.
Program: AdvancedMethodsDemo.cs
using System; using System.Linq; using System.Threading.Tasks; class Program { static void Welcome() => Console.WriteLine("Welcome to Methods!"); static void PrintStars(int count) { if (count < 0) throw new ArgumentOutOfRangeException(nameof(count)); Console.WriteLine(new string('*', count)); } static DateTime GetNowUtc() => DateTime.UtcNow; static decimal Net(decimal mrp, decimal discount) => mrp - discount; static void Increment(ref int x) => x++; static bool TryDivide(int a, int b, out int result) { if (b == 0) { result = 0; return false; } result = a / b; return true; } static int LengthOf(in string s) => s?.Length ?? 0; static int Sum(params int[] numbers) => numbers.Sum(); static decimal Price(decimal basePrice, decimal tax = 0m, bool roundUp = false) { var p = basePrice + tax; return roundUp ? Math.Ceiling(p) : p; } static (int sum, double avg) Stats(params int[] xs) { if (xs.Length == 0) return (0, 0); var sum = xs.Sum(); var avg = sum / (double)xs.Length; return (sum, avg); } static async Task FetchCountAsync() { await Task.Delay(10); return 42; } static async Task Main() { Welcome(); PrintStars(5); Console.WriteLine($"UTC now: {GetNowUtc():u}"); Console.WriteLine($"Net: {Net(1000m, 125m)}"); int n = 10; Increment(ref n); Console.WriteLine($"After Increment: {n}"); if (TryDivide(10, 2, out int q)) Console.WriteLine($"10/2 = {q}"); Console.WriteLine($"LengthOf(\"hello\") = {LengthOf("hello")}"); Console.WriteLine($"Sum(1..5) = {Sum(1,2,3,4,5)}"); var rounded = Price(99.2m, tax: 0.8m, roundUp: true); Console.WriteLine($"Rounded price = {rounded}"); var (sum, avg) = Stats(10, 20, 30); Console.WriteLine($"sum={sum}, avg={avg}"); Console.WriteLine($"Async count = {await FetchCountAsync()}"); } }
Welcome to Methods! ***** UTC now: 2025-08-22 10:00:00Z Net: 875 After Increment: 11 10/2 = 5 LengthOf("hello") = 5 Sum(1..5) = 15 Rounded price = 100 sum=60, avg=20 Async count = 42
This program demonstrates all major method features in C#:
Welcome()
PrintStars(count)
GetNowUtc()
Net(mrp, discount)
Task
AdvancedMethodsDemo.cs
csc AdvancedMethodsDemo.cs
AdvancedMethodsDemo
In C#, Properties act like smart fields. They give controlled access to private class fields with the help of get and set blocks. Think of them as variables with logic—easy to use like fields but powerful like methods.
get
set
public class Student { private string name; // private field public string Name // property { get { return name; } // Read value set { name = value; } // Write value } }
Properties improve readability, make the code maintainable, and help in data validation. For example, we can write logic inside set to ensure only valid data is stored.
Properties help us safely access private data in a class while keeping our code clean and readable.
Keeps class fields private but allows controlled access through properties.
No need for long getter and setter methods—properties make it short and simple.
Properties look like variables but internally use methods for logic.
Only allow reading or writing when required, making code safe and secure.
Properties bridge the gap between private fields and public data access in a simple way.
Properties in C# are versatile and play an important role in many real-world scenarios.
When you want to keep fields private but allow simple access for reading or writing values.
When validation or calculations are needed before saving data in private fields.
Used heavily in frameworks like ASP.NET, WPF, WinForms, and Blazor for automatic UI updates.
Properties provide clean and predictable APIs for other developers using your classes.
Properties are ideal wherever you need controlled and flexible data access in C# applications.
Before properties were introduced in C#, developers had to use separate Get and Set methods to access private fields. This ensured encapsulation but made the code look verbose and less readable.
public class Student { private string name; // private field // Old way: Use methods to get/set value public void SetName(string studentName) { if (!string.IsNullOrEmpty(studentName)) name = studentName; } public string GetName() { return name; } } class Program { static void Main() { Student s = new Student(); s.SetName("Megha"); // set value using method Console.WriteLine(s.GetName()); // get value using method } }
Properties provide a clean, simple, and flexible way to encapsulate data fields in C# while allowing easy access like variables.
public class Student { private string name; // private field // Property for Name public string Name { get { return name; } // read value set // write value { if (!string.IsNullOrEmpty(value)) name = value; } } } class Program { static void Main() { Student s = new Student(); s.Name = "Megha"; // set value like variable Console.WriteLine(s.Name); // get value like variable } }
Properties are widely used in:
public class Student { public string Name { get; set; } // no explicit field needed }
Program: StudentPropertyDemo.cs
using System; namespace School { class Student { private string name; // private field // Property for Name public string Name { get { return name; } set { if (!string.IsNullOrEmpty(value)) name = value; } } public void DisplayStudentInfo() { Console.WriteLine("Student Name: " + Name); } } class Program { static void Main() { Student s = new Student(); s.Name = "Megha"; // using property to set value s.DisplayStudentInfo(); // output student name } } }
Student Name: Megha
This program demonstrates the use of Properties in C# for data encapsulation.
Advantages:
StudentPropertyDemo.cs
csc StudentPropertyDemo.cs
StudentPropertyDemo