How do you instantiate a null reference parameter in a function?

367 views Asked by At
class A
{
    public int B { get; set; }
    public int C { get; set; }
}

private static void function(A a)
{
    if (a == null) a = new A();
    a.B = 2;
    a.C = 3;
}

A a = new A(); //a is not null
a = null; // a is null
function(a); 
//a is still null

If I use C++ analogy what I understand is that although ‘a’ is a pointer points to an object of type ‘A’ which is accessed by the function by reference, the pointer itself is used as value type. The end result is the variable ‘a’ remains null.

So my question is, what if I want to instantiate the variable as if the pointer is passed to the function by reference? Is this doable?

3

There are 3 answers

0
usr On BEST ANSWER

You can pass the variable by reference:

function(ref A a)
function(ref a);

Since you know C++, that's like a A**.

Consider refactoring the function so that it returns the new value of a:

private static A EnsureInitialized(A a) //renamed
{
    if (a == null) a = new A();
    a.B = 2;
    a.C = 3;
    return a; //now initialized
}

A a = ...; //maybe null
a = EnsureInitialized(a);

If that is truly better depends on the concrete case.

0
Hamid Pourjam On

It is all about parameters passing in C#, by value or by reference.

what you have done is call by value if you change it to call by reference it will solve the problem

private static void function(ref A a)
{
    if (a == null) a = new A();
    a.B = 2;
    a.C = 3;
}
1
David Arno On

You could use ref or out, but please don't! Having a void method return a value via a parameter is a definition code smell. Those keywords should be viewed as comparable to goto (ie the language supports them and there are some edge cases where they can be used, but they should be a tool of last resort). Instead, have your function return the value:

private static A function(A a)
{
    if (a == null) a = new A();
    a.B = 2;
    a.C = 3;
    return a;
}

A a = new A(); //a is not null
a = null; // a is null
a = function(a); // a is not null