7

In C# if we want to create a variable of type string we can use:

string str="samplestring"; // this will allocate the space to hold the string

In C#, string is a class type, so if we want to create an object, normally we have to use the new keyword. So how is allocation happening without new or constructors?

6
  • 1
    It's called a string literal.
    – BoltClock
    Oct 19, 2012 at 14:33
  • 1
    Just a note: when you say "string is a class type", don't think that this makes it different from say, an int. .NET doesn't have the primitive types that Java has, classes and structs all derive from object. Oct 19, 2012 at 14:34
  • @GrahamClark - I think 'class type' here is being used as sloppy naming for 'reference type' (i.e. the type you get if you use 'class' rather than 'struct'). It's irrelevant here anyway, as there is a 'new' going on, it's just that the compiler's concealing it.
    – Will Dean
    Oct 19, 2012 at 14:37
  • 2
    @Graham: Exactly WRONG. Value types in .NET are very different from reference types. The difference vs Java is that is Java, only built-in primitives are value types, whereas in C# you can define your own.
    – Ben Voigt
    Oct 19, 2012 at 14:37
  • @BenVoigt what I meant was unlike Java, in .Net creating an int or creating a string is creating a new object. I realise value and reference types are dealt with differently by the runtime. You can't have structs in Java? Oct 19, 2012 at 14:39

7 Answers 7

9

When you write

string str="samplestring";

compiler will generate two instructions:

  1. Firstly, ldstr gets a string literal from the metadata; allocates the requisite amount of memory; creates a new String object and pushes the reference to it onto the stack.
  2. Then stloc (or one of it's short forms, e.g. stloc.0) stores that reference in the local variable str.

Note, that ldstr will allocate memory only once for each sequence of characters.

So in example below both variables will point at the same object in memory:

// CLR will allocate memory and create a new String object
// from the string literal stored in the metadata
string a = "abc";

// CLR won't create a new String object. Instead, it will look up for an existing
// reference pointing to the String object created from "abc" literal
string b = "abc";

This process is known as string interning.

Also, as you know, in .NET strings are immutable. So the contents of a String object cannot be changed after the object is created. That is, every time you're concatenating string, CLR will create a new String object.

For example, the following lines of code:

string a = "abc";
string b = a + "xyz";

Will be compiled into the following IL (not exactly, of course):

  1. ldstr will allocate memory and create a new String object from "abc" literal
  2. stloc will store the reference to that object in the local variable a
  3. ldloc will push that reference onto the stack
  4. ldstr will allocate memory and create a new String object from "xyz" literal
  5. call will invoke the System.String::Concat on these String objects on the stack
  6. A call to System.String::Concat will be decomposed into dozens of IL instructions and internal calls. Which, in short, will check lengths of both strings and allocate the requisite amount of memory to store the concatenation result and then copy those strings into the newly allocated memory.
  7. stloc will store the reference to the newly created string in the local variable b
1
  • 1
    Firstly, ldstr gets a string literal from the metadata; allocates the requisite amount of memory; creates a new String object and pushes the reference to it onto the stack. I would say that first ldstr checks if the literal is already present in the intern "dictionary" (so if a String object has already been created for it) , if yes it returns a reference to it, otherwise it creates a new String in the intern "dictionary" based on the literal given and returns the String.
    – xanatos
    Jun 1, 2018 at 6:49
6

This is simply the C# compiler giving you a shortcut by allowing string literals.

If you'd rather, you can instantiate a string by any number of different constructors. For example:

 char[] chars = { 'w', 'o', 'r', 'd' };
 string myStr = new String(chars);
3

According to the MS documentation you do not need to use the new command to use the default string constructor.

However this does work.

char[] letters = { 'A', 'B', 'C' };
string alphabet = new string(letters);

c# Strings (from MSDN programming guide)

0
2

Strings are in fact reference types. The variable hold a reference to the value in the memory. Therefore you are just assigning the reference and not the value to the object. I would recommend you to have a look at this video from Pluralsight (you can get a free 14 days trial)

Pluralsight C# Fundamentals - Strings

Disclaimer: I am in no way related to Pluralsight. I am a subscriber and I love the videos over there

1

While everything is an object in .net there are still primitive types (int, bool, etc) that do not require instantiation. as you can see here, a string is a 4byte address ref pointing to a vector/array structure that can extend to up to 2GB. remember strings are unmutable types so when you change a string you are not editing the existing variable, but instead allocating new memory for the literal value and then changing your string pointer to point to your new memory structure. hope that helps

0

When you creates a string using literals, internally, depending on your assembly is marked with NoStringInterning flag or not, it's looks like:

String str = new String("samplestring");
// or with NoStringInterning
String str = String.Intern("samplestring");
-4

In java if you write something like that:

String s1 = "abc";
String s2 = "abc";

memory will be allocated for "abc" in so called string pool and both s1 and s2 will refer to that memory. And s1 == s2 will return true ("==" compares references). But if you write:

String s1 = new String("abc");
String s1 = new String("abc");

s1 == s2 will return false. I guess in c# it'll be the same.

2
  • I guess? Also not an answer to the question
    – lboshuizen
    Oct 19, 2012 at 15:21
  • 2
    You are incorrect c# does not behave that way. Both examples will return true, as equality operators are overridden to do comparison of the values not the references.
    – Spevy
    Oct 19, 2012 at 17:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.