Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing by reference not working

Tags:

c#

I have following code

public interface IEntity
{
// Properties
    int Id { get; set; }
}

public class Container : IEntity
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class Command
{      
    public void ApplyCommand(ref IEntity entity)
    {
        Container c = new Container() { Id = 20 };
        entity = c;
    }
}

[TestFixture]
public class ReferenceTest
{
    [Test] 
    public void Casting_ByRef_Not_ReturningValue()
    {
        Container c= new Container();
        IEntity entity = c;
        new Command().ApplyCommand(ref entity);           
        Assert.AreEqual(c.Id, 20);            
    }
}

the test is failing, shouldn't passing by reference allow object reference change ?

like image 895
np-hard Avatar asked Jun 25 '26 10:06

np-hard


2 Answers

In your test you change the object that entity is pointing to, but you're comparing the object c is pointing to.

Remember that references are copied on assignment, so that you create a new Container, let c be a reference to that object. Then you copy that reference by assigning c to entity. Now both entity and c refer to the same object. You pass ref entity into the method, thereby changing entity but not touching c.

Container c= new Container();
IEntity entity = c;
new Command().ApplyCommand(ref entity);
Assert.AreEqual(entity.Id, 20);

should definitely work.

like image 173
Joey Avatar answered Jun 27 '26 23:06

Joey


This test is working just fine. You have 2 references (c and entity) which point to a single object of type Container. When you make the call to ApplyCommand you are only changing the value of the reference entity. The reference c is unchanged and still points to the original Container object.

Here is a way to write the test to show the difference

    Container c= new Container();
    IEntity entity = c;
    new Command().ApplyCommand(ref entity);           
    Assert.IsInstanceOfType(entity, typeof(Container));
    c = (Container)entity;
    Assert.AreEqual(c.Id, 20); 
like image 28
JaredPar Avatar answered Jun 28 '26 00:06

JaredPar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!