Patrick Lewis Patrick Lewis - 17 days ago 4
C# Question

Initializing object with array of self-type as internal property: infinite initialization?

my question is basically about the manner in which C# initializes arrays.

Specifically, I am creating a large tree data structure to store words in

C#
. A subclass of this data structure, created as
node
objects, has two characteristics:
int value
and
node[] nexts
.

Wouldn't initializing a
node
object, as below, create an infinite initialization loop when
this.nexts = new node[26]
is called?

/// <summary>
/// Represents a node object for a letter.
/// </summary>
private class node {
public int value;
internal node[] nexts;
public node(bool z, int n = 0, node[] ns = null) {
this.value = n;
if (z) {
if (ns == null) { this.nexts = new node[26]; }
else { this.nexts = ns; }
}
}
}


If not and this is the correct way to initialize an object with a property being an array of itself, in what state would each element of that array exist after initialization?

Here is the entirety of the class if you're interested:

/// <summary>
/// Represents a node object for a letter.
/// </summary>
private class node {
public int value;
internal node[] nexts;
public node(bool z, int n = 0, node[] ns = null) {
this.value = n;
if (z) {
if (ns == null) { this.nexts = new node[26]; }
else { this.nexts = ns; }
}
}
public node operator++(node n) {
n.value++;
return n;
}
public node this[int i] {
get {
if (this.nexts == null) { this.nexts = new node[26]; }
return this.nexts[i];
}
set {
if (this.nexts == null) { this.nexts = new node[26]; }
this.nexts[i] = value;
}
}
}

Answer

Wouldn't initializing a node object, as below, create an infinite initialization loop when this.nexts = new node[26] is called?

No, because since node is a reference type, new node[26] just creates an array that can hold up to 26 node references; it does not create any node objects itself.

If not and this is the correct way to initialize an object with a property being an array of itself, in what state would each element of that array exist after initialization?

Each element of the array will contain a null reference.

If node were a struct, then it would create an infinite recursion.