In C#, why is String a reference type that behaves like a value type?

后端 未结 12 2569
抹茶落季
抹茶落季 2020-11-22 02:04

A String is a reference type even though it has most of the characteristics of a value type such as being immutable and having == overloaded to compare the text rather than

12条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-22 02:52

    Not only strings are immutable reference types. Multi-cast delegates too. That is why it is safe to write

    protected void OnMyEventHandler()
    {
         delegate handler = this.MyEventHandler;
         if (null != handler)
         {
            handler(this, new EventArgs());
         }
    }
    

    I suppose that strings are immutable because this is the most safe method to work with them and allocate memory. Why they are not Value types? Previous authors are right about stack size etc. I would also add that making strings a reference types allow to save on assembly size when you use the same constant string in the program. If you define

    string s1 = "my string";
    //some code here
    string s2 = "my string";
    

    Chances are that both instances of "my string" constant will be allocated in your assembly only once.

    If you would like to manage strings like usual reference type, put the string inside a new StringBuilder(string s). Or use MemoryStreams.

    If you are to create a library, where you expect a huge strings to be passed in your functions, either define a parameter as a StringBuilder or as a Stream.

提交回复
热议问题