by Dinesh Thakur Category: Introduction to C#

The Function defined with in class is called method. It is a code designed to work on the member data of class.

 

Methods are operations associated with types. To provide a type with methods is to give it some useful functionality. Often this functionality is made generally available, so that it can be utilized by other types.

A method declaration, specified within a class declaration, comprises a method-head and a method-body. The method-head is made up of the following elements (square brackets enclose those which are optional).

 

[attributes] [method-modifiers] return-type method-name ([formal-parameter-list])

 

An example of a method's name would be Welcome. To distinguish a method from a variable, it is always followed by parentheses, sometimes empty. Since a method is used to perform an assignment, its job is included between an opening curly bracket "{"and a closing curly bracket "}".Here is an example:

 

using system;

class Exercise

{

Welcome() { }

static void Main()

{

Console.writeLine();

}

}

 

If the assignment performed by a method is long, you can use many lines to define its behavior. For this reason, each bracket can be typed on its own line.

Any time you create a method, the compiler needs to know the type of value that the method would return. The type of value that a method would return is specified on the left side of the method's name.

Some, even many; of the methods used in your programs will not return a value after they have performed an assignment. When a method doesn't return a value, it is considered void. The return type of such a method is the void keyword. Here is an example:

 

using System;

class Exercise

{

void welcome()

{

}

static void Main()

{

console.writeLine();

}

}

 

Static Methods

Unlike some other languages like C/C++, Pascal, Visual Basic, etc, but like Java, C# doesn't have the notion of global function: every method must belong to a class. For this reason, every program uses at least one class and we call this primary class, the main class. Because of this feature of the language, it imposes some rules on the way methods can be called. If you create a method in the main class of your project, you should indicate that the method will always belong to this main class. The method must be created as static.

To define a method as static, type the static keyword to its left. Here is an example:

 

using system;

Class Exercise

{

Static void welcome ()

{

}

Static void Main ()

{

Console.WriteLine ();

}

}

 

As we have used the Main () function so far, the behavior of a method is defined between its delimiting curly brackets. The section inside the curly brackets is called the body of a method. In the body of the method, you can simply display a sentence. Here is an example:

 

Using system;

Class Exercise

{

Static void welcome ()

{

Console.WriteLine ("welcome to the wonderful world of c#");

}

Static void Main ()

{

Console.WriteLine ();

}

}

 

In the same way, you can use a method to perform any other assignment. After creating a method, you can use it where needed. Using a method is also referred to as calling it. If you create a simple method like the above Welcome (), to call it, type its name followed by parentheses and ending with a semi-colon. Here is an example:

 

Using System;

Class Exercise

{

static void welcome()

{

Console.WriteLine ("welcome to the wonderful world of c#");

}

static void Main()

{

Welcome ();

Console.WriteLine ();

}

}

 

Methods with return value

If a method has carried an assignment and must make its result available to other methods or other classes, the method must return a value and cannot be void. To declare a method that returns a value, provide its return type to the left of its name. Here is an example:

 

Using system;

Class Exercise

{

Static double operation ()

{

}

static void Main()

{

}

}

 

After a method has performed its assignment, it must clearly demonstrate that it is returning a value. To do this, you use the return keyword followed by the value that the method is returning. The value returned must be of the same type specified as the return type of the method. Here is an example:

 

using System;

class Exercise

{

Static double operation()

{

return 24.55;

}

static void Main()

{

}

}

 

A method can also return an expression; provided the expression produces a value that is conform to the return type. Here is an example:

 

using system;

class Exercise

{

static double operation()

{

return 24.55 * 4.16;

}

static void Main()

{

}

}

 

When a method returns a value, the compiler considers such a method as if it were a regular value. This means that you can use Console .Write () or Console.WriteLine () to display its value. To do this, simply type the name of the method and its parentheses in the Console.Write () of the Console.WriteLine () methods' parentheses. Here is an example:

 

Using system;

Class Exercise

{

Static double operation ()

{

Return 24.55;

}

Static void Main ()

{

Console.WriteLine(operation());

}

}

Methods with Arguments

Like a variable, an argument is represented by its type of value. For example, one method may need a character while another would need a string. Yet another method may require a decimal number. This means that the method or class that calls a method is responsible for supplying the right value, even though a method may have an internal mechanism of checking the validity of such a value.

The value supplied to a method is typed in the parentheses of the method and it's called an argument. In order to declare a method that takes an argument, you must specify its name and the argument between its parentheses. Because a method must specify the type of value it would need, the argument is represented by its data type and a name. If the method would not return a value, it can be declared as void.

Below examples which uses the arguments.

Call by value

When calling the methods that take one or more arguments, we made sure that we provided the needed argument. This is because an argument is always required and the calling function or class must provided a valid value when calling such a method.

 

Call by value method

 

Using System;

Class cylinder

{

static double GetTheRadius()

{

Double rad;

Do

{

Console. Write ("Radius: ");

Rad = double. Parse (console. Read Line ());

If (rad < 0)

Console. Write Line ("please enter a positive number");

} while (rad < 0);

Return rad;

}

Static double GetTheHeight ()

{

Double h;

Do

{

Console.Write ("Height: ");

h = double.Parse (console. Read Line ());

if ( h < 0 )

Console. Write Line ("please enter a positive number");

} while (h < 0);

Return h;

}

 

Static double calculateBaseArea (double rad)

{

Return rad * rad * Math.PI;

}

Static double calculateLateralArea (double rad, double hat;)

{

Return 2 * Math.PI * rad * hgt ;

}

static double calculateTotalArea(double rad, double hgt)

{

return 2 * Math. PI * rad * (hgt + rad);

}

static double calculatevolume(double rad, double hgt)

{

return Math. PI * rad * rad * hgt;

}

static void processcylinder()

{

double Radius;

double Height;

double BaseArea;

double LateralArea;

double TotalArea;

double volume;

Console.Writeline("Enter the dimensions of the cylinder");

Radius GetTheRadius();

Height = GetTheHeight();

BaseArea = calculateBaseArea(Radius);

LateralArea = calculateLateralArea(Radius, Height);

TotalArea = calculateTotalArea(Radius , Height);

volume = calculatevolume(Radius, Height);

Showcylinder(Radius, Height, BaseArea, LateralArea, TotalArea , volume); }

static void ShowCylinder(double rad, double hgt, double BArea,

double Lateral, double Total, double vol) {

console.writeLine("\ncylinder characteristics");

console.writeLine("Radius: {O}", rad);

console.writeLine("Height: {O}", hgt);

console.writeLine("Base: {O:F}", BArea);

console.writeLine("Lateral: {O:F}", Lateral);

console.writeLine("Total: {O:F}",total);

console.writeLine("volume: {O:F}", vol);

}

static void Main()

{

processCylinder();

console.writeLine();

}

}

 

OUTPUT:

 

Enter the dimensions of the cylinder

Radius: 38.26

Height: 28.48

Cylinder Characteristics

Radius: 38.26

Height: 28.48

Base: 4598.75

Lateral: 6846.44

Total: 16043.94

Volume: 130972.40

Call by reference

If you supply the argument using its name, the compiler only makes a copy of the argument's value and gives it to the calling method. Although the calling method receives the argument's value and can use in any way, it cannot (permanently) alter it. C# allows a calling method to modify the value of a passed argument if you find it necessary. If you want the calling method to modify the value of a supplied argument and return the modified value, you should pass the argument using its reference.

To pass an argument as a reference, when defining and when calling the method, precede the argument's data type with the ref keyword. You can pass 0, one, or more arguments as reference in the program or pass all arguments as reference. The decision as to which argument(s) should be passed by value or by reference is based on whether or not you want the called method to modify the argument and permanently change its value.

Here are examples of passing some arguments by reference:

 

void Area(ref double Side);

 

II The argument is passed by reference

 

bool Decision(ref char Answer, int Age);

 

II One argument is passed by reference

 

Here is an example of call by reference :

 

Method call by reference

 

using system;

class swap

{

static void swapvalue(ref int a, ref int b)

{

int temp =. a;

a = b;

b = temp;

}

public static void Main()

{

int x =10, y = 20;

console.writeLine(" values of x and yare:");

Console.writeLine(" x = " + x);

Console.writeLine(" y= " + y);

Swapvalue (ref x, ref y);

console.wrjteLine("After swapping values are:");

console.writeLine(" x "+ x);

console.writeLine(" y = " + y);

}

}

 

OUTPUT:

 

values of x and y are

 

x = 10

Y = 20

 

After swapping values are:

 

x = 20

Y = 10

Special Parameters

C# provides two special types of parameters for functions which are given below:

 

• Output parameter

• Parameter array

 

Output Parameter

 

In addition to passing values by reference, there is an output parameter used to pass result back to the calling method. Using out keyword you can declare output parameter, which does not create a new storage location like reference parameters. When a formal parameter is declared as out, the corresponding actual parameter in the calling method must also be declared as out. For Example

 

Use of output parameter

 

using system;

class Outparameter {

static void Area_of_sqaure(int x, out int y)

 

{

y = x * x;

}

public static void Main()

{

int m;

Area_of_sqaure (3, out m);

console.writLine("Area of square :"+m); }

 

OUTPUT:

 

Area of Square: 9

Parameter Array

This type of parameter is defined using params keyword and this is used to handle variable number of arguments in the method. For Example:

 

Use of Parameter Array

 

using System;

class ArrayParameter

{

static void Myfun( params int[] a)

{

console.writeLine("Elements of array are:")

foreach( int i in a)

console.writeLine(i);

}

public static void Main()

{

int [] x = { 10, 20, 30};

Myfun(x);

Myfun();

Myfun(45,67) ;

}

}

 

OUTPUT:

 

Elements of array are:

 

10

20

30

 

Elements of array are:

Elements of array are:

45

67

In the above example the Myfunc() call is equivalent to

 

Myfunc (new int [] { });

 

And Myfun (45, 67) call creates an int type array with two elements 10 and 20 and passes

the newly created array as the actual argument to the method, it is equivalent to

 

Myfun (new int [] {45, 67});

 

No additional parameters are permitted after the params keyword in a method declaration, and only one params keyword is permitted in a method declaration. If two parameters are specified in the function the params should be in last.

We can also use object type as parameter arrays. For Example:

 

public static void Main() {

objArr '(10, 20, "xyz");,

}

static void objarr ( params object [] x)

{

foreach(object i in x)

{

Console.write(i);

}

}

In the above example Objarr is passed for an array of object reference. The method call automatically builds an object array to holds the arguments, boxing value types as necessary.

Method Overloading

Multiple methods of same name with different arguments in a single program or class is called method overloading.

 

A typical program involves a great deal of names that represent variables and methods of various kinds. The compiler does not allow two variables to have the same name in the same function. Although two methods should have unique names in the same program, C# allows you to use the same name for different functions of the same program following certain rules. The ability to have various methods with the same name in the same 'program is referred to as method overloading or function overloading. The most important rule about function overloading is to make sure that each one of these methods has a different number or different type (s) of arguments.

& Concept

We will illustrate method overloading through an example:

 

Method overloading

 

using System;

public class Newproject

{

// Rectangle

static double Area(double l, double w)

{

return 1 * w;

}

// circle, overload area method

Static double Area (double R)

{

Const double PI = 3.14159;

return R * R * PI;

}

static void Main()

{

double length, width;

double Radius;

 

console.writeLine(“Enter the sides of Rectangle”);

console.write(“Length: “);

Length = double.parse(console.ReadLine());

console.write(“width: ");

width = double.parse(console.ReadLine());

 

console.writeLine(“\n Area of Rectangle:");

console.writeLine(Area(Length, width));

 

console.write("\nEnter the radius: ");

Radius = double.parse(console.ReadLine());

Console.writeLine(“ Area of circle: “);

console.writeLine(Area(Radius));

 

console.writeLine();

}

}

 

OUTPUT:

 

Enter the sides of Rectangle

Length : 10.2

Width: 3.25

Area of Rectangle : 33.15

Enter the radius : 6.27

Area of, circle: 123.5050





About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.