New Batch Starts 1st September 2025 – Join Our .NET Full Stack Development Course, Daily 6-8 AM and 8.30-10.30 PM, Register Now
+91 9989950088
info@example.com
Methods and Properties

📝 Methods in C#


A Method in C# is a block of code that performs a specific task. Think of it like a machine:

  • You give it some input (optional).
  • It processes the logic inside.
  • It gives you an output (optional).

The basic syntax of a method:

[access] [modifiers] returnType MethodName(parameterList)
{
  // code to be executed
  return value; // optional
}

Anatomy (parts) of a method:

  • access: public, private, protected, internal (who can call it)
  • modifiers: static, virtual, override, async, etc.
  • returnType: void (no value) or types like int, string, Task, etc.
  • MethodName: Verb-like names such as CalculateTax, PrintBill
  • parameterList: Inputs required by the method
  • body: Actual logic inside the method

✅ Use clear names + small, focused methods to make your code easy to read, test, and reuse.

💡 Why Use Methods in C#?


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:

♻️ Reusability

Write the logic once and call it many times wherever needed. This avoids duplicate code and saves development time.

📖 Readability

Breaking big logic into small, clearly named methods makes your code easy to understand for you and for other team members.

🧪 Testability

Small methods can be unit tested independently, ensuring your application is bug-free and works as expected.

🛠️ Maintenance

If a bug appears, you fix it in one place and the benefit reflects everywhere the method is used — reducing future issues.

🤝 Teamwork

Methods define clear inputs and outputs, so multiple developers can work together without confusion.

⚡ Performance

Well-structured methods optimize execution flow and help identify performance bottlenecks easily during testing.

✅ Using methods wisely makes your application modular, reusable, and professional.

🧩 Types of Methods in C#


Methods in C# can be classified based on two main factors:

  • Parameters (Input): Whether the method accepts data from outside.
  • Return Value (Output): Whether the method gives back a result after execution.

Based on these, there are four common combinations of methods:

Type Method Example Explanation Advantages Disadvantages When to Use
1. Without Parameters & Without Return
void SayHello() { Console.WriteLine("Hello!"); }
No input, no output. Just performs a task. Easy to implement; good for displaying messages. Not flexible; cannot reuse result in other places. When you want only an action, like logging, printing messages, or simple notifications.
2. With Parameters & Without Return
void Greet(string name) { Console.WriteLine("Hello " + name); }
Takes input but doesn’t return anything. Dynamic: Works with different inputs. No output to use further. When you need input but output is not required, like saving data in DB or printing customized messages.
3. Without Parameters & With Return
int GetNumber() { return 10; }
No input, but gives a result back. Output can be reused anywhere. No control over input values. When constant or default values are needed, like configuration settings or fixed data.
4. With Parameters & With Return
int Add(int a, int b) { return a + b; }
Takes input, processes it, and returns the result. Most flexible, reusable, works with dynamic data. Slightly more complex than others. When input and output are both required, like calculations, validations, data processing.
1️⃣ Without Parameters & Without Return
void SayHello() { Console.WriteLine("Hello!"); }

➡️ 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.

2️⃣ With Parameters & Without Return
void Greet(string name) { Console.WriteLine("Hello " + name); }

➡️ 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.

3️⃣ Without Parameters & With Return
int GetNumber() { return 10; }

➡️ 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.

4️⃣ With Parameters & With Return
int Add(int a, int b) { return a + b; }

➡️ 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.

🛠️ Best Practices:
  • Use clear and meaningful names for methods.
  • Keep methods small and focused on one task.
  • Use parameters for flexible inputs instead of hardcoding values.
  • Return values when you need to reuse the result in other places.

✅ Understanding these combinations with examples helps you write clean, reusable, and testable C# programs.

🔄 Parameters & Returns in C#


Methods in C# can be classified based on parameters (inputs) and return values (outputs). This section covers when and how to use them effectively.

1️⃣ Parameters (Inputs): Without vs With

A) Without Parameters
static void ShowWelcome()
{
  Console.WriteLine("Welcome!");
}

✔️ 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.

B) With Parameters
static void Greet(string name)
{
  Console.WriteLine($"Hello, {name}");
}

✔️ 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.

Parameter Passing Styles
  • By value (default): Method gets a copy; for reference types, you can still mutate the object.
  • ref: Pass by reference; method can replace the caller’s variable.
  • out: Method must assign it; often used to return extra values.
  • in: Read-only by reference; good for large structs.
static void Bump(ref int x) { x++; }
static bool TryParseAge(string s, out int age)
{
  return int.TryParse(s, out age);
}
Optional, Named, and Variable Arguments
static decimal NetPrice(decimal mrp, decimal discount = 0m, bool roundUp = false) { /*...*/ }
var p1 = NetPrice(1000m); // uses defaults
var p2 = NetPrice(1000m, roundUp: true); // named argument
static int Sum(params int[] numbers) => numbers.Sum();
var total = Sum(1,2,3,4); // variable count

2️⃣ Returns (Outputs): Without vs With

A) Without Return (void)
static void LogError(string message) { /* write to file */ }

✔️ Pros: Simple to implement.

⚠️ Cons: No result to chain or test easily if it only does side effects.

B) With Return (value)
static int Add(int a, int b) => a + b;

✔️ Pros: Composable, testable (pure functions).

⚠️ Cons: Harder to reason about if side effects are mixed in.

Multiple & Async Returns
  • Tuple: (int sum, double avg) Calculate(int[] xs) { ... }
  • Out parameter: bool Try... (string s, out T value)
  • Custom type: Use DTO/class for clarity and future growth
  • Async: Task for no value, Task<T> for a value later
static async Task<int> FetchCountAsync() { /* await I/O */ return 42; }
🛠️ Best Practices:
  • Use parameters for flexibility, avoid hardcoding values.
  • Prefer returning values for better testability and reuse.
  • Keep methods small; one method → one job.
  • For async work, return Task or Task<T> to stay non-blocking.
Four Core Method Combinations in C#
1. No Parameters, No Return — "Do Something Once"

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.

2. With Parameters, No Return — "Act on Given Data"

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.

3. No Parameters, With Return — "Get a Value From State"

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.

4. With Parameters, With Return — "Compute From Inputs"

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.

Why Use Methods in C#?

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.

Advantages

  • Reusability: Write logic once, call it multiple times across modules → less duplicate code.
  • Improved Readability: Break down complex logic into smaller steps with meaningful names.
  • Easy Testing: Unit test small methods independently → find bugs faster.
  • Encapsulation: Hide internal implementation; expose only necessary inputs/outputs.
  • Flexibility: Method overloading & optional parameters provide multiple ways to call the same logic.
  • Team Collaboration: Clear contracts (parameters/return types) reduce misunderstandings in large teams.

Disadvantages / Pitfalls

  • ⚠️ Too Many Tiny Methods: Causes “jump around” reading issues → hard to follow flow.
  • ⚠️ Abusing ref/out: Unexpected side effects when methods modify variables from the caller.
  • ⚠️ Hidden Global State: Methods seem pure but depend on global/static data → leads to bugs.
  • ⚠️ Confusing Overloads: Same method name with unclear parameter differences → readability suffers.
  • ⚠️ Deep Call Chains: Many nested calls make debugging harder and slightly increase performance cost.
Best Practice: Balance method size. Keep methods small, focused, and pure wherever possible. Use clear names & avoid hidden states.
C# Methods: Advanced Features Demo

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#:

  • No params & no return: Welcome() → simple actions.
  • Params & no return: PrintStars(count) → commands.
  • No params & with return: GetNowUtc() → queries.
  • Params & with return: Net(mrp, discount) → pure computations.
  • ref / out / in: Pass variables by reference or output results safely.
  • params & optional: Flexible argument count & defaults.
  • Tuple returns: Return multiple values without custom classes.
  • Async methods: Handle asynchronous operations with Task.
Using Visual Studio:
  1. Open Visual Studio.
  2. Create Console App (.NET Core) project.
  3. Paste the code in Program.cs.
  4. Press F5 to run → Output appears in the console.
Using Command-line:
  1. Save file as AdvancedMethodsDemo.cs.
  2. Open Command Prompt / Terminal.
  3. Navigate to file directory.
  4. Run → csc AdvancedMethodsDemo.cs (compile).
  5. Run → AdvancedMethodsDemo (execute).

📘 Properties in C#

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.

  • Encapsulation: Keep data safe and control access.
  • Read & Write: get → Read data, set → Update data.
  • Validation: Add logic before setting a value.
  • Clean Code: Avoid long getter/setter methods.

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.

Why do we use Properties in C#?

Properties help us safely access private data in a class while keeping our code clean and readable.

1. Encapsulation

Keeps class fields private but allows controlled access through properties.

2. Clean Code

No need for long getter and setter methods—properties make it short and simple.

3. Readability

Properties look like variables but internally use methods for logic.

4. Security

Only allow reading or writing when required, making code safe and secure.

Key Benefit

Properties bridge the gap between private fields and public data access in a simple way.

Where do we use Properties in C#?

Properties in C# are versatile and play an important role in many real-world scenarios.

1. Data Encapsulation

When you want to keep fields private but allow simple access for reading or writing values.

2. Business Logic

When validation or calculations are needed before saving data in private fields.

3. Data Binding

Used heavily in frameworks like ASP.NET, WPF, WinForms, and Blazor for automatic UI updates.

4. API Design

Properties provide clean and predictable APIs for other developers using your classes.

Practical Use

Properties are ideal wherever you need controlled and flexible data access in C# applications.

Old Style: Using Methods instead of Properties

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
    }
}

Drawbacks of Using Methods Instead of Properties:

  • Too many methods required (Get and Set for each field).
  • Less readable and harder to maintain when many fields exist.
  • No clean syntax for directly accessing values.
  • Not suitable for data-binding scenarios in ASP.NET, WPF, WinForms, etc.

C# Properties (Modern Style)

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
    }
}

Advantages of Properties:

  • No need for separate Get/Set methods
  • Cleaner, simpler, and readable code
  • Validation logic can be added inside set
  • Works well with data-binding frameworks
Common Use Cases:

Properties are widely used in:

  • Business logic for validation
  • Data encapsulation
  • ASP.NET, WPF, WinForms, Blazor for data-binding

Advantages & Disadvantages of Properties

Advantages

  • Encapsulation: Keeps fields private, allows controlled access.
  • Cleaner Syntax: Looks like variables but works like methods.
  • Validation: Apply conditions before saving data.
  • Flexibility: Create read-only or write-only properties.
  • Compatibility: Works smoothly with data-binding frameworks.

Disadvantages

  • Extra Code: More code than using public fields directly.
  • Complexity: Too many properties may complicate the class design.

Types of Properties in C#

  • Read-Write Property: get and set both present.
  • Read-Only Property: only get, no set.
  • Write-Only Property: only set, no get.
  • Auto-Implemented Property: C# automatically creates the private field.
Example of Auto-Implemented Property:
public class Student
{
    public string Name { get; set; }   // no explicit field needed
}

Quick Comparison Table

Feature Without Properties With Properties
Code Length More (Get/Set methods) Less (Single property)
Readability Less readable More readable
Encapsulation Manual logic needed Built-in with get and set
Validation Manual in methods Directly inside set
Data Binding Not suitable Suitable
C# Program using Properties

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.

  • private string name: Field is private for security.
  • public string Name {get; set;}: Property to read/write name safely.
  • DisplayStudentInfo(): Prints the student's name.
  • Main(): Creates a student object, sets the property, and displays the name.

Advantages:

  • No need for separate Get/Set methods.
  • Cleaner and more readable code.
  • Validation logic can be added inside set.
Using Visual Studio:
  1. Open Visual Studio.
  2. Create a Console App project.
  3. Paste the code into Program.cs.
  4. Press F5 to run → Output shows in console.
Using Command-line:
  1. Save file as StudentPropertyDemo.cs.
  2. Open Command Prompt.
  3. Navigate to file folder.
  4. Run → csc StudentPropertyDemo.cs
  5. Run → StudentPropertyDemo