开发者

passing by reference not working

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 ?


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.


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


The ref works perfectly, but the reference variable c is not involved.

If you run the test Assert.AreEqual(entity.Id, 20); it will pass.


try this:

 Assert.AreEqual(entity.Id, 20);   

When you write

  IEntity entity = c;  

you create another reference variable on the stack, with c's address in it. This entity variable is what you are passing by ref to the method, not the c variable.


You are changing a reference to an object you created in another method and you are pointing your IEntity instance to that object.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜