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?
If you want this to work, you need to pass by reference:
Or:
Without that,
InitializeObjectA
sets thedevice
parameter to anew 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:
This avoids the need to use
ref
orout
passing.