Search code examples
.netstringvalue-typereference-type

Would there be benefits to a struct String in .Net?


Note: This is a hypothetical discussion. I don't actually want to implement a struct String.

The .Net String class could be a value type (a struct), because it is immutable and has few members. But String isn't a value type. Probably because String was designed before nullable types were introduced, or possibly to match the behavior of Java strings.

Would it be beneficial to change String to a value type or implement a value-type variant of String? It would remove a level of indirection and match the common non-nullable case.


Solution

  • Short Answer

    A string has to have a reference type member (e.g., a char[]) in order to be of variable size. Thus any struct String type would really just be a reference type disguised as a value type anyway.


    Medium Answer

    I discussed this in more depth here. But the basic gist of my idea was: yes, you could have a string "value type," presumably something like this:

    public struct String
    {
        char[] m_characters;
    
        public String(IEnumerable<char> characters)
        {
            m_characters = characters.ToArray();
        }
    
        public char this[int index]
        {
            get { return m_characters[index]; }
        }
    
        // All those other string functions... IndexOf, Substring, etc.
    }
    

    ...but there's really no point. The above is essentially just a reference type (a wrapper around a char[]) nestled inside a shell that looks deceptively like a value type. Moreover, when you design a type this way you are getting the drawbacks of using a value type (e.g., potential for boxing) with none of the benefit (an instance of the above String type has the same memory allocation requirements as the reference type it wraps, so it buys you nothing from a GC standpoint either).