Methods, the main Method and Parameter Passing

Methods, the main Method and Parameter Passing

In C#, a method is a block of code that performs a specific task. The main method is the entry point of a C# console application, where the program execution begins. It has a specific signature:

csharp

Copy code

staticvoidMain(string[] args)

The static keyword means that the method belongs to the class and not to any instance of the class. The void keyword indicates that the method doesn’t return any value. Main is the name of the method, and string[] args is an array of strings that represents the command-line arguments passed to the program.

Parameter passing is the process of passing values to a method when it is called. C# supports three types of parameter passing:

  1. Value Parameters: This method passes a copy of the parameter value to the method. Any changes made to the parameter value inside the method do not affect the original value.
  2. Reference Parameters: This method passes the memory address of the parameter to the method. Any changes made to the parameter value inside the method will affect the original value.
  3. Output Parameters: This method is used to return more than one value from a method. An output parameter is a reference parameter that is declared using the out keyword. The method assigns a value to the output parameter, which is then returned to the caller.

Here’s an example of a method that takes a value parameter:

csharp

Copy code

publicstaticvoidAdd(int a, int b) { int result = a + b; Console.WriteLine(“Result: {0}”, result); }

Here’s an example of a method that takes a reference parameter:

csharp

Copy code

publicstaticvoidSquare(refint number) { number = number * number; Console.WriteLine(“Number squared: {0}”, number); }

Here’s an example of a method that takes an output parameter:

csharp

Copy code

publicstaticvoidDivide(int dividend, int divisor, outint quotient, outint remainder) { quotient

Methods
Method Nesting, Overloading and Variable Argument List

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?