How to return value from a function
Description
We can return a value from a method by using return
statement.
Syntax
Methods return a value to the calling routine using this form of return:
return value;
value
is the value returned.
Example
How to return value from a function
using System;// ww w . j av a2 s. c o m
class MainClass
{
public static int GetHour()
{
return 123;
}
static void Main()
{
Console.WriteLine("Hour: {0}", GetHour());
}
}
The code above generates the following result.
Example 2
The following code defines a method and return its instance from a method.
using System; /*from w w w. ja v a 2s . c o m*/
class Rect {
int width;
int height;
public Rect(int w, int h) {
width = w;
height = h;
}
public int area() {
return width * height;
}
public void show() {
Console.WriteLine(width + " " + height);
}
public Rect enlarge(int factor) {
return new Rect(width * factor, height * factor);
}
}
class MainClass {
public static void Main() {
Rect r1 = new Rect(4, 5);
Console.Write("Dimensions of r1: ");
r1.show();
Console.WriteLine("Area of r1: " + r1.area());
Console.WriteLine();
// create a rectangle that is twice as big as r1
Rect r2 = r1.enlarge(2);
Console.Write("Dimensions of r2: ");
r2.show();
Console.WriteLine("Area of r2 " + r2.area());
}
}
The code above generates the following result.
Example 3
The following code defines a method returning array.
using System; /* w ww . ja va 2s. c o m*/
class Factor {
public int[] findfactors(int num, out int numfactors) {
int[] facts = new int[80];
int i, j;
for(i=2, j=0; i < num/2 + 1; i++)
if( (num%i)==0 ) {
facts[j] = i;
j++;
}
numfactors = j;
return facts;
}
}
class MainClass {
public static void Main() {
Factor f = new Factor();
int numfactors;
int[] factors;
factors = f.findfactors(1000, out numfactors);
Console.WriteLine("Factors for 1000 are: ");
for(int i=0; i < numfactors; i++)
Console.Write(factors[i] + " ");
Console.WriteLine();
}
}
The code above generates the following result.