string s = "";
for(int i=0;i<10;i++) {
s = s + i;
}
I have been these options to answer this question.
- 1
- 11
- 10
- 2
I have this simple code, I just want to know how many string objects will be created by this code.
I have a doubt, Is string s = ""; creates no object. I dont think so, Please make me clear.
If I append string with + operator, it creates new string, so I think It will be a new object created in every iteration of for loop.
So I think there will be 11 objects created. Let me know If I'm incorrect.
String result = "1" + "2" + "3" + "4";  //Compiler will optimise this code to the below line.
String result = "1234"; //So in this case only 1 object will be created??
I followed the below link, but still its not clear.
Please cover string str and string str = null case too. What happens If we dont initialize string and when If I assign string to null. So It will be an object or no object in these two cases.
string str;
string str = null;
Later in the code, If I do.
str = "abc";
Is there any programming way to calculate number of objects?, because I think It may by a debatable topic. How can I be 100 % by doing some programming or by some tool? I cannot see this in IL code.
I have tried the below code,just to make sure whether new object is created or not. It writes 'different' for each iteration. It means it always gives me a different object, So there can a possibility of 10 or 20 objects. because it does not give me info of intermediate state(boxing for i when doing s = s + i)
    string s = "0";
    object obj = s;
    for (int i = 0; i < 10; i++)
    {
        s = s + i;
        if (Object.ReferenceEquals(s, obj))
        {
            Console.Write("Same");
        }
        else
        {
            Console.Write("Different");
        }
    }
I'm not agreed by the statement that string str = "" does not create any object. I tried this practically.
    string s = null;
    object obj = null;
    if (Object.ReferenceEquals(s, obj))
    {
        Console.Write("Same");
    }
    else
    {
        Console.Write("Different");
    }
Code writes "Same", but If I write string s = "";, It writes "Different" on console.
I have one more doubt now.
what is difference between s = s + i and s = s + i.ToString().
s = s + i.ToString() IL Code
IL_000f:  call       instance string [mscorlib]System.Int32::ToString()
IL_0014:  call       string [mscorlib]System.String::Concat(string, string)
s = s + i IL Code
IL_000e:  box        [mscorlib]System.Int32
IL_0013:  call       string [mscorlib]System.String::Concat(object, object)
So Whats difference between box and instance here
 
     
    