C# Methods

Methods are a way to organize code by grouping related functionality together. In C#, a method is a code block that contains a series of statements that can be executed whenever we need them. Methods are essential to developing modular and reusable code, making them an essential part of any C# programmer's toolkit.

Declaring a Method in C#

The syntax for declaring a method in C# is as follows:

1<access-modifier> <return-type> <method-name>(<parameter-list>) 2{ 3 // Method body 4}

The access modifier specifies the level of access that other code has to the method. The return type is the data type of the value returned by the method. The method name is the name of the method, and the parameter list is a comma-separated list of input parameters.

Here is an example of a simple method that adds two numbers and returns the result:

1public int AddNumbers(int num1, int num2) 2{ 3 int result = num1 + num2; 4 return result; 5}

In this example, the method has a public access modifier, an integer return type, and two integer input parameters.

Calling a Method in C#

Once a method is declared, it can be called from any other part of the program. To call a method in C#, we use the following syntax:

1<method-name>(<argument-list>)

Here is an example of calling the AddNumbers method we declared earlier:

1int sum = AddNumbers(3, 5);

In this example, we pass the values 3 and 5 as arguments to the AddNumbers method, and the method returns the sum of these numbers, which we assign to the variable "sum".

C# Method Return Type

The return type of a method specifies the type of data that the method returns to the calling code. A method can have a return type of void if it does not return any value.

Here is an example of a method that returns a string:

1public string Greet(string name) 2{ 3 return "Hello, " + name + "!"; 4}

In this example, the Greet method takes a string parameter "name" and returns a string containing a greeting.

C# Method Parameters

A method parameter is a variable that is passed to a method when it is called. Parameters can be used to pass data to a method, and they can also be used to receive data from a method.

Here is an example of a method that takes two integer parameters and returns their product:

1public int Multiply(int num1, int num2) 2{ 3 return num1 * num2; 4}

In this example, the Multiply method takes two integer parameters "num1" and "num2" and returns their product.

Built-in Methods

C# provides a number of built-in methods that are part of the language. These include methods for working with strings, arrays, and other data types.

Here is an example of using the built-in Math.Sqrt method to calculate the square root of a number:

1double number = 25; 2double squareRoot = Math.Sqrt(number);

In this example, we assign the value 25 to the "number" variable and use the Math.Sqrt method to calculate its square root.