Microsoft.NET

……………………………………………….Expertise in .NET Technologies

Methods in C#

Posted by Ravi Varma Thumati on February 12, 2015

A method is a code block that contains a series of statements. A program causes the statements to be executed by calling the method and specifying any required method arguments. Methods are also called as functions and it may or may not return a value. Methods are mainly allows you to define the logic once and use it at many places.

  • Methods are used for re-usability of code.
  • Methods make the maintenance of application easier.

Methods are of two types, static methods and instance methods.

Syntax

[attributes]

Access-modifier return-type method-Name(parameters)

{

Method body

}

Following are the various elements of a method:

  • Access Specifier: This determines the visibility of a variable or a method from another class.
  • Return type: A method may return a value. The return type is the data type of the value the method returns. If the method is not returning any values, then the return type is void.
  • Method name: Method name is a unique identifier and it is case sensitive. It cannot be same as any other identifier declared in the class.
  • Parameter list: Enclosed between parentheses, the parameters are used to pass and receive data from a method. The parameter list refers to the type, order, and number of the parameters of a method. Parameters are optional; that is, a method may contain no parameters.
  • Method body: This contains the set of instructions needed to complete the required activity.

Return type can any valid data type or if we don’t want to return any type then we can use void

Parameters are optional.

Example

class TestMotorcycle : Motorcycle

{

public override double GetTopSpeed()

{

return 108.4;

}

static void Main()

{

TestMotorcycle moto = new TestMotorcycle();

 

moto.StartEngine();

moto.Drive(5, 20);

double speed = moto.GetTopSpeed();

Console.WriteLine(“My top speed is {0}”, speed);

}

}

Calling a Methods using parameters

using System;

namespace CalculatorApplication

{

class NumberManipulator

{

public int FindMax(int num1, int num2)

{

/* local variable declaration */

int result;

 

if (num1 > num2)

result = num1;

else

result = num2;

 

return result;

}

static void Main(string[] args)

{

/* local variable definition */

int a = 100;

int b = 200;

int ret;

NumberManipulator n = new NumberManipulator();

 

//calling the FindMax method

ret = n.FindMax(a, b);

Console.WriteLine(“Max value is : {0}”, ret );

Console.ReadLine();

}

}

Different types of Method Parameters:

The parameters of a method, if any, are declared by the method’s formal-parameter-list.

There are four kinds of formal parameters:

  • Value parameters, which are declared without any modifiers.
  • Reference parameters, which are declared with the ref modifier.
  • Output parameters, which are declared with the out modifier.
  • Parameter arrays, which are declared with the params modifier.

Value Parameters:

A parameter declared with no modifiers is a value parameter. A value parameter corresponds to a local variable that gets its initial value from the corresponding argument supplied in the method invocation.

using System;

namespace Sample

{

class program

{

public static void sampleMethod(int j)

{

j=100;

}

static void Main(string[] args)

{

/* local variable definition */

int i = 0;

//calling the FindMax method

sampleMethod(i);

Console.WriteLine(i);

Console.ReadLine();

}

}

Pass by Value

 

I —————-à i=0

 

J —————-à J=100

I and J are pointing to different memory locations. Operations variables are will not affect the values of the other variables

Output:

0

Reference Parameters:

A variable of a reference type does not contain its data directly; it contains a reference to its data. When you pass a reference-type parameter by value, it is possible to change the data pointed to by the reference, such as the value of a class member. However, you cannot change the value of the reference itself; that is, you cannot use the same reference to allocate memory for a new class and have it persist outside the block.

using System;

 

namespace Sample

{

class program

{

public static void sampleMethod( ref int j)

{

j=100;

}

static void Main(string[] args)

{

/* local variable definition */

int i = 0;

//calling the FindMax method

sampleMethod(ref i);

Console.WriteLine(i);

Console.ReadLine();

}

}

I —————-à

I=0/100 – (10024 memory location)

J —————-à

In this case I and J are both pointing to same memory location. Operations one variable will affect the

Value of the other variables.

Output:

100

Out Parameters:

A parameter declared with an out modifier is an output parameter. Similar to a reference parameter, an output parameter does not create a new storage location. Instead, an output parameter represents the same storage location as the variable given as the argument in the method invocation.

using System;

class Test

{

static void SplitPath(string path, out string dir, out string name) {

int i = path.Length;

while (i > 0) {

char ch = path[i – 1];

if (ch == ‘\\’ || ch == ‘/’ || ch == ‘:’) break;

i–;

}

dir = path.Substring(0, i);

name = path.Substring(i);

}

static void Main() {

string dir, name;

SplitPath(“c:\\Windows\\System\\hello.txt”, out dir, out name);

Console.WriteLine(dir);

Console.WriteLine(name);

}

}

Usually, a method returns value with return keyword. Unfortunately, a return modifier can return only one value at a time. Sometime, your C# program required to return multiple values from a single method. In this situation, you need such type of function that can produce multiple output result from a single function. The output parameter C# lets your program to return multiple values.

Parameter Array:

A parameter declared with a params modifier is a parameter array. If a formal parameter list includes a parameter array, it must be the last parameter in the list and it must be of a single-dimensional array type. For example, the types string[] and string[][] can be used as the type of a parameter array, but the type string[,] cannot. It is not possible to combine the params modifier with the modifiers ref and out.

A parameter array permits arguments to be specified in one of two ways in a method invocation:

  • The argument given for a parameter array can be a single expression of a type that is implicitly convertible to the parameter array type. In this case, the parameter array acts precisely like a value parameter.
  • Alternatively, the invocation can specify zero or more arguments for the parameter array, where each argument is an expression of a type that is implicitly convertible to the element type of the parameter array. In this case, the invocation creates an instance of the parameter array type with a length corresponding to the number of arguments, initializes the elements of the array instance with the given argument values, and uses the newly created array instance as the actual argument.

Except for allowing a variable number of arguments in an invocation, a parameter array is precisely equivalent to a value parameter of the same type.

using System;

class Test

{

static void F(params int[] args) {

Console.Write(“Array contains {0} elements:”, args.Length);

foreach (int i in args)

Console.Write(” {0}”, i);

Console.WriteLine();

}

static void Main() {

int[] arr = {1, 2, 3};

F(arr);

F(10, 20, 30, 40);

F();

}

}

 

Produces the output

Array contains 3 elements: 1 2 3

Array contains 4 elements: 10 20 30 40

Array contains 0 elements:

Method Parameters and Method Arguments:

Parameters

parameter represents a value that the procedure expects you to pass when you call it. The procedure’s declaration defines its parameters.

When you define a Function or Sub procedure, you specify a parameter list in parentheses immediately following the procedure name. For each parameter, you specify a name, a data type, and a passing. You can also indicate that a parameter is optional. This means that the calling code does not have to pass a value for it.

The name of each parameter serves as a local variable in the procedure. You use the parameter name the same way you use any other variable.

Arguments

An argument represents the value that you pass to a procedure parameter when you call the procedure. The calling code supplies the arguments when it calls the procedure.

When you call a Function or Sub procedure, you include an argument list in parentheses immediately following the procedure name. Each argument corresponds to the parameter in the same position in the list.

In contrast to parameter definition, arguments do not have names. Each argument is an expression, which can contain zero or more variables, constants, and literals. The data type of the evaluated expression should typically match the data type defined for the corresponding parameter, and in any case it must be convertible to the parameter type.

 

Leave a comment