简体   繁体   中英

Strings in Java and C#

I recently moved over to C# from Java and wanted to know how do we explicitly define a string thats stored on heap.

For example:

In Java, there are two ways we can define Strings:

String s = "Hello" //Goes on string pool and is interned
String s1 = new String("Hello") //creates a new string on heap

AFAIK, C# has only one way of defining String:

String s = "Hello" // Goes on heap and is interned

Is there a way I can force this string to be created on heap, like we do in Java using new operator? There is no business need for me to do this, its just for my understanding.

In C#, strings are ALWAYS created on the heap. Constant strings are also (by default) always interned.

You can force a non-constant string to be interned using string.Intern() , as the following code demonstrates:

string a1 = "TE";
string a2 = "ST";
string a = a1 + a2;

if (string.IsInterned(a) != null)
    Console.WriteLine("a was interned");
else
    Console.WriteLine("a was not interned");

string.Intern(a);

if (string.IsInterned(a) != null)
    Console.WriteLine("a was interned");
else
    Console.WriteLine("a was not interned");

In C#, the datatypes can be either

  1. value types - which gets created in the stack (eg int, struct )
  2. reference type - which gets created in the heap (eg string, class)


Since strings are reference types and it always gets created in a heap.

Like Java:

char[] letters = { 'A', 'B', 'C' }; 

string alphabet = new string(letters);

and various ways are explained in this link .

In the .net platform, strings are created on the heap always. If you want to edit a string stay: string foo = "abc"; string foo = "abc"+ "efg"; it will create a new string, it WON'T EDIT the previous one. The previous one will be deleted from the heap. But, to conclude, it will always be created on the heap.

On .Net your literal string will be created on the heap and a reference added to the intern pool before the program starts.

Allocating a new string on the heap occurs at runtime if you do something dynamic like concatenating two variables:

String s = string1 + string2;

See: http://msdn.microsoft.com/library/system.string.intern.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM