Search code examples
c#.netoutref

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.


Solution

  • 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.