You don't need to have a reference to an integer - just put your integer inside a reference type - which is almost what you've done already. Just change this line:
Console.WriteLine(foo);
to:
Console.WriteLine(bar.Value);
Then add an appropriate accessor to the class Bar
, and remove the compile errors (remove the ref
keywords).
An alternative approach is to pass the integer to a function by reference:
static void AddOne(ref int i)
{
i++;
}
static void Main()
{
int foo = 7;
AddOne(ref foo);
Console.WriteLine(foo);
}
Output:
8