C# -

Methods

Methods in C# are blocks of code that perform a specific task. They help in organizing code, making it more readable, and promoting reusability. This tutorial covers various aspects of methods in C#, including method declaration, parameters, return types, method overloading, and best practices.


1. Method Declaration

A method in C# is declared with a return type, a name, and optional parameters. The basic syntax is:

        
            namespace MethodExamples;

class Program
{
    // Method declaration syntax
    [access_modifier] [return_type] [method_name]([parameter_list])
    {
        // Method body
    }
}
        
    

Example: A simple method that adds two numbers and returns the result.

        
            namespace MethodExamples;

class Program
{
    static void Main(string[] args)
    {
        int result = Add(3, 5);
        Console.WriteLine($"Result: {result}");
    }

    static int Add(int a, int b)
    {
        return a + b;
    }
}
        
    

2. Parameters

Methods can take parameters, which are inputs passed to the method. Parameters are specified within the parentheses in the method declaration.

Example:
        
            namespace MethodExamples;

class Program
{
    static void Main(string[] args)
    {
        Greet("Alice");
        Greet("Bob", 25);
    }

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

    static void Greet(string name, int age)
    {
        Console.WriteLine($"Hello, {name}! You are {age} years old.");
    }
}
        
    

C# supports different types of parameters, including optional parameters, named parameters, and parameter arrays.


3. Return Types

The return type of a method specifies the type of value the method returns. If a method does not return a value, its return type is void.

Example:
        
            namespace MethodExamples;

class Program
{
    static void Main(string[] args)
    {
        string greeting = GetGreeting("Alice");
        Console.WriteLine(greeting);
    }

    static string GetGreeting(string name)
    {
        return $"Hello, {name}!";
    }
}
        
    

A method can return any data type, including primitive types, objects, and even other methods.


4. Method Overloading

Method overloading allows you to define multiple methods with the same name but different parameters. This enables you to perform different tasks with methods that conceptually perform the same operation.

Example:
        
            namespace MethodExamples;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(Add(3, 5));
        Console.WriteLine(Add(2.5, 4.3));
        Console.WriteLine(Add(1, 2, 3));
    }

    static int Add(int a, int b)
    {
        return a + b;
    }

    static double Add(double a, double b)
    {
        return a + b;
    }

    static int Add(int a, int b, int c)
    {
        return a + b + c;
    }
}
        
    

5. Additional Examples

C# provides advanced features for methods, such as optional parameters, named parameters, and parameter arrays. Here are some additional examples to illustrate these concepts.

Method with Optional Parameters:
        
            namespace MethodExamples;

class Program
{
    static void Main(string[] args)
    {
        PrintMessage("Hello, World!");
        PrintMessage("Hello, World!", 3);
    }

    static void PrintMessage(string message, int repeatCount = 1)
    {
        for (int i = 0; i < repeatCount; i++)
        {
            Console.WriteLine(message);
        }
    }
}
        
    
Method with Named Parameters:
        
            namespace MethodExamples;

class Program
{
    static void Main(string[] args)
    {
        DisplayInfo(name: "Alice", age: 30, city: "New York");
        DisplayInfo(age: 25, city: "Los Angeles", name: "Bob");
    }

    static void DisplayInfo(string name, int age, string city)
    {
        Console.WriteLine($"Name: {name}, Age: {age}, City: {city}");
    }
}
        
    
Method with Parameter Array:
        
            namespace MethodExamples;

class Program
{
    static void Main(string[] args)
    {
        int sum1 = AddNumbers(1, 2, 3);
        int sum2 = AddNumbers(4, 5, 6, 7, 8);
        Console.WriteLine($"Sum1: {sum1}");
        Console.WriteLine($"Sum2: {sum2}");
    }

    static int AddNumbers(params int[] numbers)
    {
        int sum = 0;
        foreach (int number in numbers)
        {
            sum += number;
        }
        return sum;
    }
}
        
    

6. Best Practices


Conclusion

Understanding and using methods effectively is crucial for writing clean and maintainable C# code. This tutorial covered method declaration, parameters, return types, method overloading, additional examples, and best practices for creating and using methods in C#.