Reputation: 95
It seems weird that you can define a class that has a member field that is of that class.
public class Person
{
public string Name { get; set; }
public Person Spouse { get; set; }
}
Now if I call that class:
var jane = new Person();
var jim = new Person();
jane.Spouse = jim;
jim.Spouse.Spouse = jane;
The last line causes an error. But I'm having a bit of trouble imaging what what the jim.Spouse.Spouse call is doing. It should evaluate jim.spouse first which is null so it causes an error right? If I assert jim.Spouse = jane first then it should work? But then I'm essentially saying jane.spouse = jane.
If a class has a field of the same type then what is it doing to the class? Is it just allowing two instances of the class to have a relationship? The class references itself so it's inheriting from itself? I'm kinda confused and also wondering if this is bad practice.
Upvotes: 1
Views: 1812
Reputation: 30092
You've asked several things here, but in general it's fine to have a reference to the same type (even the same instance) on an object.
public class Thing {
private string name;
public Thing(string name) {
this.name = name;
}
public Thing Other {
get;
set;
}
public override string ToString() {
return this.name;
}
}
var o = new Thing("Foo");
o.Other = o;
Debug.WriteLine(o.Other.Other.Other.Other.ToString()); // Could go on forever
jim.Spouse
is a null reference, so you can't set a property on it.jim.Spouse = jane;
, then you should be able to set a reference. In this case you would want to say jim.Spouse.Spouse = jim;
, since jim.Spouse
evaluates to jane
.Upvotes: 5