alex.mironov
alex.mironov

Reputation: 2942

Why I can't initialize object in the same manner (without using ref)?

I would like to initialize an object of type B from another class A, why I still get null? Is it possible to do it without using ref and out modifiers?

    class A
    {
        public void Initialize(B value)
        {
            if (value == null)
            {
                value = new B();
            }
        }
    }

    class B
    {

    }

    class Program
    {
        static void Main(string[] args)
        {
            A a = new A();
            B b = null;
            a.Initialize(b);
        }
    }

[upd.] I thought the b variable could be passed by ref because of it's the instance of the class.

Upvotes: 2

Views: 178

Answers (2)

Henk Holterman
Henk Holterman

Reputation: 273621

It is possible, just make Initialize() a function:

class A
{
    public B Initialize(B value)
    {
        if (value == null)
        {
            value = new B();
        }
        return value;
    }
}

And call it like:

    static void Main(string[] args)
    {
        A a = new A();
        B b = null;
        b = a.Initialize(b);
    }

This is a good solution, the data flow is clearly visible. No surprises.

But otherwise, just use a ref (not an out) : public void Initialize(ref B value) and call a.Initialize(ref b);


I thought the b variable could be passed by ref because of it's the instance of the class.

To answer that you need very precise wording: b is not the instance of a class. b is a reference to an instance. Instances never have a name.

And b is treated just like a value type: the reference is passed by value to the method. Unless you use ref.

Upvotes: 6

nos
nos

Reputation: 229264

public void Initialize(B value)

Inside this method, value is just like a local variable, when you assign something to it, the caller is not affected.

Is it possible to do it without using ref and out modifiers?

No not in this manner, that's what ref/out is for.

You could just return the new object though, and assign it in the caller.

 public B Initialize() {
     return new B();
  }

... 
  b = a.Initialize();

Upvotes: 1

Related Questions