Search code examples
c#objectinstantiation

Object initialized in other class's method isn't referenced by calling method in C#


I have a class where I declare an object, but don't initialize the object. Then I pass the object to a method in another class for initialization. What I expect to happen is that the object in the calling class will now have a reference to the initialized object, but instead it is null.

Here is an example of what I mean:

class MainClass
{
    ObjectA foo;

    OtherClass.InitializeObjectA(foo);

    // why is foo null over here?
}

class OtherClass
{
    public static void InitializeObjectA(ObjectA device)
    {
        device = new ObjectA();
    }
}

My problem is that device when I try to use foo after calling InitializeObjectA() it is still pointing to null! If I change InitializeObjectA() to out ObjectA device it works. Can anyone explain why this is needed?


Solution

  • If you want this to work, you need to pass by reference:

    public static void InitializeObjectA(ref ObjectA device)
    {
    

    Or:

    public static void InitializeObjectA(out ObjectA device)
    {
    

    Without that, InitializeObjectA sets the device parameter to a new ObjectA(), but that will not affect the caller, because, by default, references are passed by value.

    Note that, if you're just trying to initialize, returning an instance instead of void is often a better way to handle this:

    public static ObjectA InitializeObjectA()
    {
         return new ObjectA();
    }
    

    This avoids the need to use ref or out passing.