Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ref?

Tags:

c#

ref

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;
    }
}
like image 356
Dima Kozyr Avatar asked Jul 30 '26 13:07

Dima Kozyr


2 Answers

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;
}
like image 118
p.s.w.g Avatar answered Aug 02 '26 02:08

p.s.w.g


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.

like image 32
TypeIA Avatar answered Aug 02 '26 02:08

TypeIA