function Return
In this chapter you will learn:
- How to return value from a function
- How to return an object value from a method
- How to return a value of an array from a method
Return value from a function
Methods return a value to the calling routine using this form of return:
return value;
value
is the value returned.
using System;/*j a v a 2 s . co m*/
class MainClass
{
public static int GetHour()
{
return 123;
}
static void Main()
{
Console.WriteLine("Hour: {0}", GetHour());
}
}
The code above generates the following result.
Return an object
The following code defines a method and return its instance from a method.
using System; // j av 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.
Return an array
The following code defines a method returning array.
using System; // j a v a 2s . c om
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.
Next chapter...
What you will learn in the next chapter:
- How to write recursive methods
- Display a string in reverse by using recursion
- How to calculate fibonacci value in C#
Home » C# Tutorial » Class