Why string is sealed

Viewed 3287

I am curious why System.String is sealed?

I know, I can do whatever I need to do not inheriting it, but still -- why?

There are a lot of classes that, by nature, are strings having specific methods and properties. Those are identifiers, emails, names etc.

Object oriented design suggests to encapsulate functionality in a specific class. And here we have weird situation that the most usable fundamental type in the most popular object framework is not extendable.

Thank you.

EDITED.

Comment regarding immutability. It is easy to hide all state-related things in private methods and allow child classes to have read-only access to class's data.

// Safe inheritable immutable string (pseudocode).
class String
{
   // Private state
   private byte[] state;
   private void EditState(byte[]) {}
   // Protected read-only access to state
   protected byte getReadOnlyData() {}
   // Available to child classes overridable methods.
   protected virtual getHashCode() {}
   protected virtual xxx() {}
}

In fact most of objects in real-world applications are strings. All those serials, ASINs, IMEI etc, as well as names, comments, are string by their nature. We get them as strings from databases, or they typed as string somewhere in text boxes on a web page or canned by barcode scanners etc.

And it would be really nice, more secure and much more elegant to have strings with specific features instead of inventing multiple classes, more or less doing the same.

3 Answers

FYI 'implicit operators' are an alternative to extending sealed classes via inheritance. As long as new classes are only strongly typed strings. Those classes then become usable where string is expected... which simplifies usage

public class Email
{
    string m_stringfrom; // no other fields 

   public static implicit operator string(Email email)
   {
        return email.m_stringfrom;
    }
   public static implicit operator Email(string email)
   {
        return new Email() {
            m_stringfrom = email // only field in email !
        };
   }
}

void test()
{
    Email work_email = "test@domain.com";
    Display(work_email);
}
void Display( string toBeDisplayed)
{

}
Related