C# - Methods

A method is a collection of statements that work together to complete a task. There is always a class in a C# programme that has a Main method.

Following are the various elements of a method:

  • Access Specifier: This controls whether a variable or method from a different class is visible.
  • Return type: A value may be returned by a method. The data type of the value that the method returns is known as the return type. The return type is void if the method is not returning any values.
  • Method name:The method name is case-sensitive and a unique identifier. It cannot match any other defined identifier in the class.
  • List of parameters: The parameters, which are enclosed in parenthesis, are used to send and receive data from a method.The kind, quantity, and arrangement of a method's parameters are referred to as its parameter list. It is possible for a method to have no parameters, as parameters are optional.
  • Method body: This contains the set of instructions needed to complete the required activity.

Here's an example of a method:

public int AddNumbers(int a, int b)
    return a + b; 

Method Parameters

Parameters allow methods to receive input data. They are defined within the parentheses after the method name and specify the type and name of each parameter.

Return Type

The return statement in a method is used to return a value based on the method's return type. If the method doesn't return anything, its return type is specified as void.

Method Overloading

C# supports method overloading, allowing you to define multiple methods with the same name but different parameter lists. This is based on the number, type, or order of parameters.

public int AddNumbers(int a, int b) 
    return a + b; 

public double AddNumbers(double a, double b) 
    return a + b;

Access Modifiers

Access modifiers determine the visibility of methods. They can be public, private, protected, or internal, among others.

public:Accessible from any class.

private: Accessible only within the same class.

protected: Accessible within the same class or derived classes.

internal: Accessible within the same assembly.

Method Calling

To call a method, use the method name followed by parentheses and, if needed, pass arguments that match the method's parameter list.

int result = AddNumbers(5, 10); // Calling the method

Method Scope

Variables declared inside a method are usually local to that method (unless they are declared at a higher scope).

It's important to comprehend C# methods because they help to improve code organisation and readability, as well as encapsulate functionality and encourage code reuse.