Methods in C#: Declaration, Parameters, Overloading, Return Values & Best Practices

1. Methods in C#

Q: What is a method in C#?

A method is a block of code that performs a specific task, encapsulated within a class or struct. It has a name, can take input parameters, and may return a value. Methods promote code reusability and modularity in C# programs.

Q: What are the key components of a method in C#?

Syntax:

accessModifier returnType MethodName(parameterList) {
    // Code
}

2. Declaring and Calling Methods

Q: How do you declare a method in C#?

Declare a method within a class or struct using the syntax above. Specify the access modifier, return type, name, and parameters.

Example:

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

Q: How do you call a method in C#?

Call a method using its name and providing required arguments. For instance methods, use an object; for static methods, use the class name or call directly within the same class.

Example:

var obj = new MyClass();
int result = obj.Add(5, 3); // Instance method call
int staticResult = MyClass.StaticMethod(); // Static method call

Q: What is the difference between instance and static methods?

Example:

class MyClass {
    public int InstanceMethod() { return 1; }
    public static int StaticMethod() { return 2; }
}

Q: Can you give an example of declaring and calling methods in C#?

using System;

namespace MethodsBasics
{
    class Program
    {
        // Instance method
        public string Greet(string name)
        {
            return $"Hello, {name}!";
        }

        // Static method
        public static int Square(int number)
        {
            return number * number;
        }

        static void Main(string[] args)
        {
            // Calling instance method
            Program p = new Program();
            string greeting = p.Greet("Krishna");
            Console.WriteLine(greeting); // Output: Hello, Krishna!

            // Calling static method
            int result = Square(5);
            Console.WriteLine($"Square of 5: {result}"); // Output: Square of 5: 25
        }
    }
}

Output:

Hello, Krishna!
Square of 5: 25

3. Parameters and Return Values

Q: What are parameters in C# methods?

Parameters are variables that accept input values when a method is called. C# supports:

Q: What are return values in C#?

A return value is the data a method sends back to the caller, specified by the return type. Use return to send the value, or void for no return. Multiple values can be returned using tuples (C# 7.0+).

Q: Can you give an example of methods with parameters and return values?

using System;

namespace ParametersAndReturn
{
    class Program
    {
        // Value parameter
        public int Add(int a, int b = 0) // Optional parameter
        {
            return a + b;
        }

        // Ref parameter
        public void Increment(ref int number)
        {
            number++;
        }

        // Out parameter
        public void Divide(int a, int b, out int quotient, out int remainder)
        {
            quotient = a / b;
            remainder = a % b;
        }

        // Params array
        public int Sum(params int[] numbers)
        {
            int total = 0;
            foreach (int num in numbers)
            {
                total += num;
            }
            return total;
        }

        // Tuple return
        public (int min, int max) GetMinMax(int a, int b)
        {
            return (Math.Min(a, b), Math.Max(a, b));
        }

        static void Main(string[] args)
        {
            Program p = new Program();

            // Value and optional parameter
            Console.WriteLine($"Add: {p.Add(5, 3)}"); // 8
            Console.WriteLine($"Add with default: {p.Add(5)}"); // 5

            // Ref parameter
            int x = 10;
            p.Increment(ref x);
            Console.WriteLine($"After increment: {x}"); // 11

            // Out parameter
            p.Divide(10, 3, out int q, out int r);
            Console.WriteLine($"Quotient: {q}, Remainder: {r}"); // Quotient: 3, Remainder: 1

            // Params array
            Console.WriteLine($"Sum: {p.Sum(1, 2, 3, 4)}"); // 10

            // Tuple return
            var (min, max) = p.GetMinMax(7, 2);
            Console.WriteLine($"Min: {min}, Max: {max}"); // Min: 2, Max: 7
        }
    }
}

Output:

Add: 8
Add with default: 5
After increment: 11
Quotient: 3, Remainder: 1
Sum: 10
Min: 2, Max: 7

4. Method Overloading

Q: What is method overloading in C#?

Method overloading allows multiple methods with the same name but different parameter lists (number, types, or order) in the same class. The compiler selects the appropriate method based on the arguments provided during the call.

Q: What are the rules for method overloading?

Q: Can you give an example of method overloading in C#?

using System;

namespace MethodOverloading
{
    class Program
    {
        // Overloaded methods
        public double CalculateArea(double radius)
        {
            return Math.PI * radius * radius; // Circle
        }

        public double CalculateArea(double length, double width)
        {
            return length * width; // Rectangle
        }

        public double CalculateArea(int side)
        {
            return side * side; // Square
        }

        static void Main(string[] args)
        {
            Program p = new Program();

            Console.WriteLine($"Circle area: {p.CalculateArea(5.0):F2}"); // Circle
            Console.WriteLine($"Rectangle area: {p.CalculateArea(4.0, 6.0):F2}"); // Rectangle
            Console.WriteLine($"Square area: {p.CalculateArea(3)}"); // Square
        }
    }
}

Output:

Circle area: 78.54
Rectangle area: 24.00
Square area: 9

Q: How does method overloading differ from C/C++?

Q: What are common mistakes with methods in C#?

Declaring/Calling:

Parameters/Return Values:

Overloading:

Q: What are best practices for methods in C#?

Declaring/Calling:

Parameters/Return Values:

Overloading:

General:

Frequently asked questions

What is a method in C#?

A method is a reusable block of code that performs a specific task. It can take parameters, return a value, and is defined inside a class or struct.

What is the difference between instance and static methods in C#?

Instance methods require an object to call and can access instance members; static methods belong to the class, are called without an instance, and can only access static members.

How do you pass parameters in C# methods?

C# supports value parameters (default), ref (reference), out (output), in (read-only reference), optional parameters with defaults, and params for variable arguments.

What is method overloading in C#?

Method overloading allows multiple methods with the same name but different parameter lists (number, types, or order) in the same class.

How do you return values from methods in C#?

Use the return keyword with a value matching the return type. For multiple values, use tuples or custom classes.

What are ref, out, and params keywords in C#?

ref passes a reference to modify the original variable; out requires assigning a value inside the method; params allows a variable number of arguments as an array.

What are best practices for writing methods in C#?

Use descriptive names, keep methods small and focused, prefer static for utilities, use in/ref/out/params appropriately, document overloads, and leverage expression-bodied syntax.

What are common mistakes with methods in C#?

Forgetting to instantiate for instance methods, misusing ref/out, creating ambiguous overloads, and writing overly long or complex methods.