My variable Index
doesn't change when I passed it as parameter in the method:
int Index = 0;
void Method (int Index_)
{
Index_++;
}
Method(Index);
Console.WriteLine(Index);
The console print 0 despite the index should increase
In C#, when you pass a primitive (int
, char
, float
, etc) parameter into a function, the function creates a local copy of that variable. if you want to pass the parameter by reference you can use the ref
keyword, which basically tells the function to use the original variable rather than creating a new local copy of it.
You can use it like this:
int Index = 0;
void Method (ref int Index_)
{
Index_++;
}
Method(ref Index);
Console.WriteLine(Index);