I'm learning to use ref, but can't understand, why I'm getting an error?
class A
{
public void ret(ref int variable)
{
variable = 7;
}
static int Main()
{
int z = 5;
ret(ref z); // Error: Need a reference on object
Console.WriteLine(z); // it will be 7 as I understand
return 0;
}
}
The problem isn't with the ref parameter. It's that ret is an instance method, and you can't call an instance method without a reference to an instance of that type.
Try making ret static:
public static void ret(ref int variable)
{
variable = 7;
}
You're using ref correctly. The error is actually because ret() is an instance method, while Main() is static. Make ret() static as well and this code will compile and work as you expect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With