Question

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;
    }
}
Was it helpful?

Solution

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;
}

OTHER TIPS

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.

Your method is not static.You need to make is static like this:

public static void ret(ref int variable)
{
    variable = 7;
}

Since ret is an instance method you can't access it without creating an object of the type.

Try making the method ret as static method like public static void ret(ref int variable)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top