How many string objects are created?

I have the following C # code:

string stg1 = "String 1";
string stg2 = "String 2";
string stg3 = "String 3";
string stg4;
stg4 = stg1 + stg3;
stg4 = stg4 + stg2 + stg3;
stg4 = "";
stg3 = "";

How many string objects are created?
I think 7 string objects are created: "String 1", "String 2", "String 3", stg1 + stg3, stg4 + stg2 + stg3, ""and "". I was not sure that the 4th operator ( string stg4;) creates a string object, and I read somewhere that when assigning a string, an empty string ""does not create an object, but I do not think that this is true. What do you guys think?

+5
source share
2 answers

I read somewhere that assigning a string to an empty string "" does not create an object, but I do not think it is true. What do you guys think?

This is not entirely true. There is most likely a string instance created for an empty string.

, ; . , , , string , , . "".

, , , . , , .

, .

, , , stg4 + stg2 + stg3 , , , , .

, : stg4 + stg2, , stg3, . . string.Concat, (Concat Concat(params string[] args), ), Concat , string, n-1.

+11

All Articles