Start C# here

Study C#.. Go ahead ! !

Monday, July 28, 2008

Methods with return type in C#

Here in this topic we will check how we can create Methods with a return type.

We use methods with a return type when we need a method to return some values to the place from which the method has been called. Return type can be of any type. If we need to return and Integer we can use int keyword. Likewise we can return string, float, double, Class etc...

While we create a method with a return type it should have the keyword "return" followed by the value of the type the method returns...
If the method is returning an integer we can write it as return 0. Because 0 is an integer.

Let's check an example for methods with a return type...
-----------------------------------------
Example 1:-
------------
//Method with an integer return type
public int Add()
{
int iResult=10+20;

return iResult;
}
------------
Here we have used the return keyword to return the value inside the integer variable iResult. So if we call the method Add() we will be getting the sum of the two numbers.

Example 2:-
------------
//Method with a string return type
public string HelloWorld()
{
return "Hello World!";
}
------------
In the above example we have created a method with a string return type. Here we are returning the string "Hello World!".
-----------------------------------------

While we call a method with a return type it should also be stored into the same type. Like wise we can create method(s) with return types.



Now we'll see methods with parameters that return values.


Parameters are used inside a method to pass values to a method at the time of call. We must specify the types of variables inside the method parenthesis for accepting values. Parameters which we declare inside the method parenthesis is also known as Function signatures. While we pass values to methods which accepts values, it should be passed in the exact order in which we have defined that method.

Let's check a method with parameters:-
-----------------------------------------

class Calculator
{

public int AddNumber(int num1, int num2)
{
int result;
result = num1 + num2;
return result;
}

}
-----------------------------------------

Here AddNumber is the name of the method. Since the access specifier is public, the method can be accessed from outside the class also. The method is taking two integers as the parameters and returning the value stored in the result variable. So, we must have to pass two integer values while we call this method. The values passed to this method will be stored in num1 and num2 variables.

eg:-

static void Main(string[] args)
{
int iResult=AddNumber(10,20);
Console.WriteLine(i);
}

Here we have called the method AddNumber. Since the method returns an integer it is assigned to an integer variable. Likewise we should do in each function which have return type..

No comments: