Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In .NET, what is the rationale for Strings initializing to null?

I understand that String is an object, as opposed to say Int, and object variables generally don't point to anything unless you create the object. So I know how it works.

But, in terms of simple, practical programming, why doesn't .NET initialise a string as empty (""), as that is surely the most common use of the string variable - as a string, not as an object?

I've never (yet) had need for a string to be null, that is "not a string". It seems to be a rare requirement. I'm unable to say an int variable is null, so why do so with string? Having it as an option is undoubtedly necessary, but why does .NET make it null to begin with, when int etc. are given proper initial values?

I'm asking because I like to understand not just how something works but why, as it reduced my desire to rant about how weird it seems. :)

like image 875
ingredient_15939 Avatar asked Oct 14 '11 04:10

ingredient_15939


1 Answers

Strings are not initialized as null. You are confusing initialization with declaration. Whenever you declare a variable like:

 Foo myFoo;

It starts out as null until you actually call its constructor. Like so:

Foo myFoo = new Foo();

Now traditionally you don't call constructors for the string class, you instantiate them with string literals like this:

string myString = "foo";

There are constructors for the string class though, a few of them, but they all take some array of characters / bytes to use to create the string. What never happens is this:

// initialize an empty string ("")
string myString = new string();

This is because the string class is immutable, that is once it has been instantiated you can never change it, you can only create a new string and set your variable to point to it (this is why all the methods of the string class return a new string rather than changing the one you called the method on). So really it makes no sense to initialize to some default value because once you had done so you would be stuck with it.

like image 51
Matthew Avatar answered Nov 15 '22 06:11

Matthew