Home > Enterprise >  Object A properties change through Object B properties as references
Object A properties change through Object B properties as references

Time:12-15

Lets say I have object A which properties I want to assign to Object B and by modifying object B I'd like Object A reference type properties to change also. Objects are not the same.

Class A 
{
   public string Link1 { get; set;}
}

Class B 
{        
   public string Link { get; set;}
}

public void ProcessLink(ref B b)
{
    b.Link = serviceX.GetLink(); // this should set Obj A.Link value too
}

How code should look like? so that Objects A property Link1 would be updated by calling

var a = new A(){ Link1 = null};
var b = new B() {Link = a.Link1};
ProcessLink(ref B);

now a.Link1 is equal to b.Link

CodePudding user response:

You're describing B being a proxy for A. One way to do this would be to give class B a reference to an instance of A. Instead of auto-properties, write getters and setters for B that actually operate on the A. You could give A a method to obtain an instance of B.

An example of this pattern is CancellationTokenSource (analogous to A) and CancellationToken (B). The tokens are proxies that expose the cancelled property of the source, but don't let you cancel it.

Consider whether it makes more sense to make B an interface that A implements.

  • Related