string s = ""; for(int i=0;i<10;i++) { s = s + i; }
I was this option to answer this question.
I have this simple code, I just want to know how many string objects this code will create.
I have a doubt, Is string s = "";
does not create any object. I donβt think so. Please let me understand.
If I add a line with the + operator, it creates a new line, so I think it will be a new object created at each iteration of the for loop.
So, I think that 11 objects will be created. Let me know if I'm wrong.
String result = "1" + "2" + "3" + "4";
I followed the link below, but is still unclear.
Link1
Please attach string str
and string str = null
case. What happens if we do not initialize the string and when If we assign the string to a null value. Thus, in these two cases, it will be an object or an object.
string str; string str = null;
Later in code if I do this.
str = "abc";
Is there any programming way to calculate the number of objects ?, because I think this could be a debatable topic. How can I be 100% busy with programming or some kind of tool? I do not see this in IL code.
I tried the code below to make sure the new object is created or not. He writes "different" for each iteration. This means that it always gives me another object, so there may be a possibility of 10 or 20 objects. because it does not give me information about the intermediate state (box 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 do not agree with the statement that string str = ""
does not create any object. I tried it in practice.
string s = null; object obj = null; if (Object.ReferenceEquals(s, obj)) { Console.Write("Same"); } else { Console.Write("Different"); }
The code writes "Same", but if I write string s = "";
, he writes "Console" to the console.
I now have one more doubt.
what's the 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 what is the difference between field and instance here