mr fat
mr fat

Reputation: 95

Defining a class that has a field of the same class. Class with self references?

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

Answers (1)

Evan Trimboli
Evan Trimboli

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
  1. You're correct in your assertion about the exception. It throws because jim.Spouse is a null reference, so you can't set a property on it.
  2. If you set 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.
  3. Regarding the fields of the same type, it's no different to anything else. It's just a variable with a type that the class uses. It is not an uncommon pattern for a type to have a reference to something else of the same type. For example, an Employee class might have a reference to a Manager, who is also an Employee. Another common example is tree implementations, in a binary tree a Node will have a reference to a Left/Right Child node.

Upvotes: 5

Related Questions