Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference type not passed as reference

Tags:

c#

I have this strange problem in my unit tests. See the following code

_pos = null;
Utilities.InitPOS(_pos, trans);
Assert.IsNotNull(_pos); //fails

The InitPOS functions looks like

public static void InitPOS(POSImplementation pos, Transaction newTransaction)
{
    pos = new POSImplementation();
    pos.SomeProp = new SomeProp();
    pos.SomeProp.SetTransaction(newTransaction);
    Assert.IsNotNull(pos);
    Assert.IsNotNull(pos.SomeProp);
}

The object POSImplementation is an implementation of some interface and it is a class, so it is a reference type...

Any idea?

like image 935
Henri Avatar asked Mar 24 '26 10:03

Henri


2 Answers

You're passing a reference to an object to InitPOS (namely a null reference), not a reference to the variable named _pos. The effect is that the new POSImplementation instance is assigned to the local variable pos in the InitPOS method, but the _pos variable remains unchanged.

Change your code to

_pos = Utilities.InitPOS(trans);
Assert.IsNotNull(_pos);

where

public static POSImplementation InitPOS(Transaction newTransaction)
{
    POSImplementation pos = new POSImplementation();
    // ...
    return pos;
}
like image 142
dtb Avatar answered Mar 25 '26 23:03

dtb


pos = new POSImplementation();

Just what are you doing there, if someone is passing pos into the method already? Are you missing a ref attribute on that parameter maybe?

like image 42
leppie Avatar answered Mar 26 '26 00:03

leppie