Method Parameter
In this chapter you will learn:
What is method parameter
The parameters define the input value for a method.
The following code defines a method called
add
, which adds two int
type variables together.
add
method has two parameters, a
and b
.
When calling the add
method we must provide data for a
and b
.
using System;/* j a va 2s. co m*/
class Program
{
static int add(int a, int b)
{
int result = a + b;
Console.WriteLine(result);
return result;
}
static void Main(string[] args)
{
add(1, 2);
}
}
Pass int value to a function
using System;/* ja v a 2 s . c o m*/
class MainClass
{
public static void Main() {
int SomeInt = 6;
int s = Sum(5, SomeInt);
Console.WriteLine(s);
}
public static int Sum(int x, int y) // Declare the method.
{
return x + y; // Return the sum.
}
}
The code above generates the following result.
Parameters are local
using System;//from j av a 2s . c o m
class Program
{
static void change(int i)
{
i = i + 1;
Console.WriteLine("in change method:" + i);
}
static void Main(string[] args)
{
int i = 2;
change(i);
Console.WriteLine("in main method:" + i);
}
}
The output:
From the output we can see that changing the value in change method has no effect on the variable i in main method.
For reference type parameters the value of the reference is copied not the object itself.
The following code defines a class Rectangle
.
Class is a reference type.
The change method accepts the Rectangle
type as its parameter.
In the change method new value is assigned to the parameter.
using System;/* j a v a 2s.com*/
class Rectangle
{
public int Width = 5;
public int Height = 5;
}
class Program
{
static void change(Rectangle r)
{
r.Width = 10;
}
static void Main(string[] args)
{
Rectangle r = new Rectangle();
Console.WriteLine(r.Width);
change(r);
Console.WriteLine(r.Width);
}
}
The output:
We can see that the main
method gets the changed value from change method.
The change
method changes the value from the reference.
To see the effect of a copied reference we can change the code above as follows.
using System;/* j a v a 2 s . c o m*/
class Rectangle
{
public int Width = 5;
public int Height = 5;
}
class Program
{
static void change(Rectangle r)
{
r = null;
}
static void Main(string[] args)
{
Rectangle r = new Rectangle();
Console.WriteLine(r.Width);
change(r);
Console.WriteLine(r.Width);
}
}
The output:
Even if we set the reference in change
method to null,
the r
in the main
method still points the rectangle object.
Next chapter...
What you will learn in the next chapter: