Default string value... empty? (C#)

I’ve declared a public array of strings in my class without assigning values to them. I intend to enter them for each object in Unity’s inspector pane. I won’t always use the full array (some objects will have less options associated with them,) so I loop through it, and when it finds the first null element in the array it sets int usableLength to that index and stops looping.

Strangely, I found that usableLength always remained at 0. But if I use
if (array.Equals(“”)), or IsNullOrEmpty for that matter,
it works. I thought C# was supposed to initialize all types to null by default? It’s not preventing me from making progress now that I’ve figured it out, but I’m curious as to why.

I believe this is what is going on:

Uninitialized strings in C# will have a null default value.
Uninitialized public strings in Unity (or rather, in a MonoBehavior) will have an empty value.

This demonstrates:

string myString;
string[] myStrings;

public string myPublic;
public string[] myPublics;

void Start() {
	myStrings = new string[2];
	Debug.Log(myString);     // null
	Debug.Log(myStrings[0]); // null
	Debug.Log(myPublic);     // ""
	Debug.Log(myPublics[0]); // ""
}

And, as discussed in the comments, I would try to avoid having arrays with “holes”.
You can either use the inspector array size, or if it does not need to be inspector-exposed, use a generic List instead.

Finally - if you still prefer (or must) keep an array with holes, then you already found your answer. It would be item == "" if its a public inspector array, or item == null and in any case, you better off using IsNullOrEmpty.

Monobehaviour’s public fields will have serialization once they get involved in some prefabs. That’s why they got objects assigned when you check them in Editor or Player.