Why is string a reference type?

前端 未结 3 783
悲&欢浪女
悲&欢浪女 2020-12-03 18:25

Why is string a reference type, even though it\'s normally primitive data type such as int, float, or double.

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-03 19:07

    String is a reference type, not a value type. In many cases, you know the length of the string and the content of the string, in such cases, it is easy to allocate the memory for the string. but consider something like this.

    string s = Console.ReadLine();
    

    is it not possible to know the allocation details for "s" in compilation time. User enters the values and all the entered string/line is stored in the s. So, strings are stored on heap so that memory is reallocated to fit the content for the string s. And reference to this string is stored on stack.

    To learn more please read: .net zero by petzold

    Read: Garbage collection from CLR Via C# for allocation details on stack.

    Edit: Console.WriteLine(); to Console.ReadLine();

提交回复
热议问题