T
Tony Johansson
Hi!
Assume I have variables such as width and height in main and pass these two
value types to a method called GetArea.
In this case the method can read the values of these two variables so that
it can calculate the area. The method can't change the value of the original
values that exist in main but it can change the formel copied value of
height and width so the returned result is based on the copied values in
GetArea.
But now to my question is it possible to prevent the two values that is
copied to the formel parameters in GetArea
to be changed in the GetArea method.
Below is an example that I call method GetArea from main and pass the value
of 2 for height and the value of 4 for width.
In the static method GetArea I change height by adding 1 and I add 1 to the
width.
So in main as you can see I say that "The area of 2 and 4 is 15 which is
not correct because that the height and width was changed in the GetArea
method by on.
So is it possible to use const or something else to prevent the copied
valued to be changed in the method GetArea ?
static int GetArea(int height, int width)
{
height++;
width++;
int result = height * width;
return result;
}
static void Main(string[] args)
{
int height = 2;
int width = 4;
Console.WriteLine("The area of: {0} and {1} is {2}", height,width,
GetArea(height, width));
}
//Tony
Assume I have variables such as width and height in main and pass these two
value types to a method called GetArea.
In this case the method can read the values of these two variables so that
it can calculate the area. The method can't change the value of the original
values that exist in main but it can change the formel copied value of
height and width so the returned result is based on the copied values in
GetArea.
But now to my question is it possible to prevent the two values that is
copied to the formel parameters in GetArea
to be changed in the GetArea method.
Below is an example that I call method GetArea from main and pass the value
of 2 for height and the value of 4 for width.
In the static method GetArea I change height by adding 1 and I add 1 to the
width.
So in main as you can see I say that "The area of 2 and 4 is 15 which is
not correct because that the height and width was changed in the GetArea
method by on.
So is it possible to use const or something else to prevent the copied
valued to be changed in the method GetArea ?
static int GetArea(int height, int width)
{
height++;
width++;
int result = height * width;
return result;
}
static void Main(string[] args)
{
int height = 2;
int width = 4;
Console.WriteLine("The area of: {0} and {1} is {2}", height,width,
GetArea(height, width));
}
//Tony