Hi guys.
One of the situations I have come across several times is where an object is used by another object but is not a child of the other object. In other words Object A can have one or more Object B related to it, but each one of those Object B can exist without Object A - i.e. they are both root objects. I believe this is known as a Using relationship rather than a Parent Child relationship. Anyway, in such a case it is often beneficial to provide an easy way to get a collection of Object B (or in actual fact Object B info objects) through Object A. I have found two ways to do this:-
1) Implement a property
[NotUndoable()] //Don't want this saved in N-Level undo!
private ObjectBCollection _objectBCol;
public ObjectBCollection ObjectBCol
{
get
{
if (_objectBCol == null)
_objectBCol = ObjectBList.GetObjectBList(_objectAKey));
return _objectBCol;
}
}
2) Implement a property that always refetches the list.
public ObjectBCollection ObjectBCol
{
get
{
return ObjectBList.GetObjectBList(_objectAKey));
}
}
Are either of these preferable? Is there a better way to do it? I hope I have explained this OK, it is not easy.
TIA
I prefer option #2, because I usually just want to provide navigational convenience, and I don't want to be responsible for the lifetime of this other object.
Option #1 is good, however, if I'm using this other object within the containing object - in which case maintaining a reference is a fine thing. But then you need to realize that you've assumed control for that object's lifetime to some degree - in that the object instance will stay around as long as your containing object stays around.
If you do #1, make sure to make it as [NonSerialized] as well, because you probably don't want this (presumably root) object moving around the network with your object - that could get a bit messy (unless you plan for it).
Rocky
Thanks for pointing out the NonSerialized attribute, I'd overlooked that.
Hi Malloc
Interesting. I haven't come across that before. Care to demonstrate what you mean with a little code? I have googled it but didn't find much help.
Thanks.
Razorkai,
Forget what I said before, I misread your post. Both options are acceptable. It really depends on what you are doing. If object A is going to use the reference of object B throughout the class I would go with option 1, else I would go with option 2. Instead of checking for a null reference in option 1, you could load the reference to object B in object A's constructor. This avoids the checking for null everytime the property is accessed.Copyright (c) Marimer LLC