Question

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.

Was it helpful?

Solution

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");

OTHER TIPS

In C#, the datatypes can be either

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


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

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.

Like Java:

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

string alphabet = new string(letters);

and various ways are explained in this link.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top