Search code examples
c#.netstringclrdefault-constructor

Why does the String class not have a parameterless constructor?


int and object have a parameterless constructor. Why not string?


Solution

  • Update:

    To provide more information for you.

    You don't have an empty Constructor with a string, however you do have String.Empty. The reason is because a string is an immutable object every instance of a string you modify is actually creating a new string in memory.

    For instance: string name = ""; though it is an empty string it will still hold around twenty bytes. Where the string.Empty will only hold around four or eight bytes. So though they mean the same thing, one is more efficient than the other.

    However I believe you want an empty Constructor to do manipulation that may be more commonly handled by the StringBuilder. Some really nice usage between the two can be found here (Determine performance hit / usage).

    Some additional information on the string can be found here. They are immutable thus the contents cannot be changed afterwards.

    Example:

    string first = "Greg "; // Creates string "first" in memory.
    string last = "Arrigotti "; // Creates string "last" in memory.
    string name = first + last; // Creates string "name" in memory.
    

    As you edit one of these, it is simply creating a whole new string in memory. If you are looking at a way to potentially handler user data in a field where no middle name exist for instance, the empty string may contain valid usage.

    Hopefully these point you in the proper direction.