In this post, we will see how to resolve Function doesn’t change value
Question:
I don’t know how function in Visual Studio C# work. My variable just change value in the function but after that it goes back to old value. I don’t know why.static void Plus(int a, int n)
{
for(int i = 0; i < n; i++)
{
a = a + 1;
}
}
static void Main(string[] args)
{
Console.WriteLine("a = ");
int a = int.Parse(Console.ReadLine());
Console.WriteLine("n = ");
int n = int.Parse(Console.ReadLine());
Plus(a, n);
Console.WriteLine($"after plus a = {a}");
}
[/code]
Best Answer:
If you want to changea
not its local copy, declare a
as ref
: // note “ref int”, not just “int”
static void Plus(ref int a, int n)
{
for(int i = 0; i < n; i++)
{
a = a + 1;
}
}
static void Main(string[] args)
{
Console.WriteLine("a = ");
int a = int.Parse(Console.ReadLine());
Console.WriteLine("n = ");
int n = int.Parse(Console.ReadLine());
Plus(ref a, n); // when calling we use "ref" as well
Console.WriteLine($"after plus a = {a}");
}
[/code]
// we just return the result (note int instead of void)
static int Plus(int a, int n)
{
for(int i = 0; i < n; i++)
{
a = a + 1;
}
return a;
}
static void Main(string[] args)
{
Console.WriteLine("a = ");
int a = int.Parse(Console.ReadLine());
Console.WriteLine("n = ");
int n = int.Parse(Console.ReadLine());
a = Plus(a, n); // we assign result to a
Console.WriteLine($"after plus a = {a}");
}
[/code]
If you have better answer, please add a comment about this, thank you!
Source: Stackoverflow.com
Leave a Review