See the the ? mark for the question.
public class Person
{
public Int16 ID { get; private set; }
public string Name { get; private set; }
public List<Toy> Toys { get; private set; }
public Person(Int16 id, string name, List<Toy> toys)
{ ID = id; Name = name; Toys = toys; }
}
public class Toy
{
public string Name { get; private set; }
public Person Owner { get; private set; }
public Toy(Person owner, string name)
{ Owner = owner; Name = name; }
}
The problem is with the Person CTOR. How to pass toys to the Person ctor? Toy needs Owner in the Toy ctor but that Owner has not yet been built yet.
I understand I can move Toys out of the Person CTOR and make the set public. Assume you only get the toys you are born with – the private set; has a purpose. And I understand that what I am asking for may not be possible.
Like anyone really cares but Toy only needs to know it Owners name so I may just modified Toys.
public class Toy
{
private Person owner;
private string ownerName;
public string Name { get; private set; }
public String OwnerName
{
get
{
if (!string.IsnullOrEmpty(ownerName)) return ownerName;
elseif (owner != null) return owner.Name;
else throw new exception("homelesstoy");
}
public Toy( string name, Person owner)
{
Name = name; Owner = owner;
// new toy need to write it to DB
}
public Toy( string name, string _ownerName)
{
Name = name; ownerName = _ownerName;
}
}
In a whacked kind of way this is better. If my toy is is my car and they have my keys I don’t want them to know my address. From my name the police can find me if the car is recovered.
Why is the setter on
Ownerprivate? I can understand your point about the setter onToysin thePersonclass.If you removed that constraint, you could create a backing store (full property) and then loop the toys list in the
Personconstructor and doitem.Owner = this.This would allow you to set
Owneronly once and subsequent calls to the setter would be exceptional. You wouldn’t need to change the constructor, because you could still do:One problem that I see is that this Toy-Owner relationship doesn’t model the real world. Children are sometimes born with a slew of toys at their disposal, but toys are hardly ever manufactured with an immediate owner. Even after a toy is created and given to someone, it can be given to someone else.
I think the conceptual details are tripping you up logically.
edit:
forgot the constructor…