Max Toro
Max Toro

Reputation: 28608

why use string constructor with char array for constants?

I found this piece of code and I'd like to understand why the developer used the string constructor with a char array instead of just a literal constant string:

static string atomLang = new String("lang".ToCharArray());

Upvotes: 2

Views: 262

Answers (1)

Douglas
Douglas

Reputation: 54877

The only reason I can think of is to avoid getting a reference to the interned instance of the string.

string str1 = "lang";
string str2 = "lang";
string str3 = new String("lang".ToCharArray());

Console.WriteLine(object.ReferenceEquals(str1, str2));   // Output: true
Console.WriteLine(object.ReferenceEquals(str1, str3));   // Output: false

Not that this will have any practical effects on your code (other than marginal performance differences).

Upvotes: 5

Related Questions