Henri
Henri

Reputation: 5113

Reference type not passed as reference

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?

Upvotes: 3

Views: 267

Answers (3)

Tormod
Tormod

Reputation: 4583

You don't pass the instance by reference, you pass the reference by value.

Upvotes: 1

dtb
dtb

Reputation: 217401

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;
}

Upvotes: 8

leppie
leppie

Reputation: 117330

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?

Upvotes: 1

Related Questions