Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

variable doesn't upgrade as parameter

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading