C# - Methods and Parameters

C# Methods and Parameters - Complete Tutorial with Examples

C# Methods and Parameters

This tutorial provides a comprehensive and SEO-optimized explanation of C# methods and parameters. You'll learn how to define and use methods in C#, understand return types, method overloading, and how different types of parameters such as value parameters, reference parameters (ref, out), optional parameters, named arguments work. This guide is ideal for beginners and experienced developers looking to master methods in C# programming.

What are Methods in C#?

In C#, methods are blocks of code that perform a specific task. They help in code reusability and organization by encapsulating logic into manageable units. Every C# program has at least one method β€” the Main() method which is the program's entry point.

Syntax of a Method

access_modifier return_type MethodName(parameter_list)
{
    // Method body
}

Example: Simple Method

public void Greet()
{
    Console.WriteLine("Welcome to C# Methods!");
}

Types of Methods in C#

  • Void Methods (do not return value)
  • Value Returning Methods
  • Static Methods
  • Instance Methods
  • Parameterized Methods
  • Overloaded Methods

1. Void Method

These methods do not return any value.

public void ShowMessage()
{
    Console.WriteLine("This is a void method.");
}

2. Value Returning Method

These methods return a value using the return keyword.

public int GetNumber()
{
    return 100;
}

3. Static Method

Can be called using the class name without creating an instance.

public static void PrintStatic()
{
    Console.WriteLine("This is a static method.");
}

4. Instance Method

Must be called through an object of the class.

public void DisplayInstance()
{
    Console.WriteLine("Instance method called.");
}

Method Parameters in C#

Parameters allow you to pass data to methods. You can define multiple parameters separated by commas.

public void PrintMessage(string message)
{
    Console.WriteLine(message);
}

Calling with Parameters

PrintMessage("Hello from parameterized method!");

Parameter Passing Techniques

1. Value Parameters (Default)

Value types are passed by value, meaning a copy is passed to the method.

public void Increment(int num)
{
    num++;
    Console.WriteLine("Inside method: " + num);
}
int number = 10;
Increment(number);
Console.WriteLine("Outside method: " + number);

2. Reference Parameters - ref Keyword

Allows a method to modify the caller's variable value.

public void AddTen(ref int x)
{
    x += 10;
}
int a = 5;
AddTen(ref a);
Console.WriteLine(a); // Output: 15

3. Output Parameters - out Keyword

Used to return multiple values from a method.

public void GetCoordinates(out int x, out int y)
{
    x = 10;
    y = 20;
}
int x, y;
GetCoordinates(out x, out y);
Console.WriteLine($"X: {x}, Y: {y}");

4. Variable Number of Arguments - params Keyword

Allows you to pass a variable number of parameters.

public void PrintNames(params string[] names)
{
    foreach (string name in names)
    {
        Console.WriteLine(name);
    }
}
PrintNames("John", "Alice", "Bob");

5. Optional Parameters

You can assign default values to parameters, making them optional.

public void GreetUser(string name = "Guest")
{
    Console.WriteLine($"Hello, {name}!");
}
GreetUser();         // Output: Hello, Guest!
GreetUser("Lakshmi");// Output: Hello, Lakshmi!

6. Named Arguments

Specify parameters by name when calling a method, useful in methods with multiple optional parameters.

public void OrderDetails(string item, int quantity, string address)
{
    Console.WriteLine($"{quantity} {item}(s) will be shipped to {address}.");
}
OrderDetails(item: "Laptop", address: "Chennai", quantity: 1);

Method Overloading in C#

Method overloading means having multiple methods with the same name but different signatures (number or type of parameters).

public void Show()
{
    Console.WriteLine("No parameters");
}

public void Show(string name)
{
    Console.WriteLine("Name: " + name);
}

public void Show(int id, string name)
{
    Console.WriteLine($"ID: {id}, Name: {name}");
}

Calling Overloaded Methods

Show();
Show("Lakshmi");
Show(1, "Janakiraman");

Return Statement in Methods

The return keyword is used to return a value from a method. If the return type is not void, the method must contain a return statement.

public double GetPi()
{
    return 3.14159;
}

Real-world Example

public class Calculator
{
    public int Add(int a, int b)
    {
        return a + b;
    }

    public int Subtract(int a, int b)
    {
        return a - b;
    }

    public int Multiply(int a, int b)
    {
        return a * b;
    }

    public double Divide(int a, int b)
    {
        if (b == 0)
            throw new DivideByZeroException("Cannot divide by zero.");
        return (double)a / b;
    }
}
Calculator calc = new Calculator();
Console.WriteLine("Add: " + calc.Add(5, 3));
Console.WriteLine("Subtract: " + calc.Subtract(5, 3));
Console.WriteLine("Multiply: " + calc.Multiply(5, 3));
Console.WriteLine("Divide: " + calc.Divide(10, 2));

Mastering C# methods and parameters is crucial for building scalable, reusable, and maintainable code. By understanding how parameters are passed, using method overloading, and implementing ref, out, and optional arguments, you gain better control over your method behavior. This foundational knowledge is not only essential for day-to-day C# development but also frequently asked in technical interviews.

Beginner 5 Hours
C# Methods and Parameters - Complete Tutorial with Examples

C# Methods and Parameters

This tutorial provides a comprehensive and SEO-optimized explanation of C# methods and parameters. You'll learn how to define and use methods in C#, understand return types, method overloading, and how different types of parameters such as value parameters, reference parameters (ref, out), optional parameters, named arguments work. This guide is ideal for beginners and experienced developers looking to master methods in C# programming.

What are Methods in C#?

In C#, methods are blocks of code that perform a specific task. They help in code reusability and organization by encapsulating logic into manageable units. Every C# program has at least one method — the Main() method which is the program's entry point.

Syntax of a Method

access_modifier return_type MethodName(parameter_list) { // Method body }

Example: Simple Method

public void Greet() { Console.WriteLine("Welcome to C# Methods!"); }

Types of Methods in C#

  • Void Methods (do not return value)
  • Value Returning Methods
  • Static Methods
  • Instance Methods
  • Parameterized Methods
  • Overloaded Methods

1. Void Method

These methods do not return any value.

public void ShowMessage() { Console.WriteLine("This is a void method."); }

2. Value Returning Method

These methods return a value using the return keyword.

public int GetNumber() { return 100; }

3. Static Method

Can be called using the class name without creating an instance.

public static void PrintStatic() { Console.WriteLine("This is a static method."); }

4. Instance Method

Must be called through an object of the class.

public void DisplayInstance() { Console.WriteLine("Instance method called."); }

Method Parameters in C#

Parameters allow you to pass data to methods. You can define multiple parameters separated by commas.

public void PrintMessage(string message) { Console.WriteLine(message); }

Calling with Parameters

PrintMessage("Hello from parameterized method!");

Parameter Passing Techniques

1. Value Parameters (Default)

Value types are passed by value, meaning a copy is passed to the method.

public void Increment(int num) { num++; Console.WriteLine("Inside method: " + num); }
int number = 10; Increment(number); Console.WriteLine("Outside method: " + number);

2. Reference Parameters - ref Keyword

Allows a method to modify the caller's variable value.

public void AddTen(ref int x) { x += 10; }
int a = 5; AddTen(ref a); Console.WriteLine(a); // Output: 15

3. Output Parameters - out Keyword

Used to return multiple values from a method.

public void GetCoordinates(out int x, out int y) { x = 10; y = 20; }
int x, y; GetCoordinates(out x, out y); Console.WriteLine($"X: {x}, Y: {y}");

4. Variable Number of Arguments - params Keyword

Allows you to pass a variable number of parameters.

public void PrintNames(params string[] names) { foreach (string name in names) { Console.WriteLine(name); } }
PrintNames("John", "Alice", "Bob");

5. Optional Parameters

You can assign default values to parameters, making them optional.

public void GreetUser(string name = "Guest") { Console.WriteLine($"Hello, {name}!"); }
GreetUser(); // Output: Hello, Guest! GreetUser("Lakshmi");// Output: Hello, Lakshmi!

6. Named Arguments

Specify parameters by name when calling a method, useful in methods with multiple optional parameters.

public void OrderDetails(string item, int quantity, string address) { Console.WriteLine($"{quantity} {item}(s) will be shipped to {address}."); }
OrderDetails(item: "Laptop", address: "Chennai", quantity: 1);

Method Overloading in C#

Method overloading means having multiple methods with the same name but different signatures (number or type of parameters).

public void Show() { Console.WriteLine("No parameters"); } public void Show(string name) { Console.WriteLine("Name: " + name); } public void Show(int id, string name) { Console.WriteLine($"ID: {id}, Name: {name}"); }

Calling Overloaded Methods

Show(); Show("Lakshmi"); Show(1, "Janakiraman");

Return Statement in Methods

The return keyword is used to return a value from a method. If the return type is not void, the method must contain a return statement.

public double GetPi() { return 3.14159; }

Real-world Example

public class Calculator { public int Add(int a, int b) { return a + b; } public int Subtract(int a, int b) { return a - b; } public int Multiply(int a, int b) { return a * b; } public double Divide(int a, int b) { if (b == 0) throw new DivideByZeroException("Cannot divide by zero."); return (double)a / b; } }
Calculator calc = new Calculator(); Console.WriteLine("Add: " + calc.Add(5, 3)); Console.WriteLine("Subtract: " + calc.Subtract(5, 3)); Console.WriteLine("Multiply: " + calc.Multiply(5, 3)); Console.WriteLine("Divide: " + calc.Divide(10, 2));

Mastering C# methods and parameters is crucial for building scalable, reusable, and maintainable code. By understanding how parameters are passed, using method overloading, and implementing ref, out, and optional arguments, you gain better control over your method behavior. This foundational knowledge is not only essential for day-to-day C# development but also frequently asked in technical interviews.

Related Tutorials

Frequently Asked Questions for General

line

Copyrights © 2024 letsupdateskills All rights reserved