Reputation:
I have some -really long- string literals in my application. Does it differ to define them in a method like:
public string DoSomething()
{
string LongString = "...";
// ...
}
or as a const
field in the lass like:
private const string LongString = "...";
public string DoSomething()
{
// ...
}
The DoSomething()
method will be called many many times, is the LongString
created and destroyed each time if I define it inside the method, or the compiler takes care?
Upvotes: 1
Views: 105
Reputation: 9017
There is no difference between the two, the string will not be created and destroyed many times in the method. .NET uses string interning, so distinct string literals are only defined once.
Upvotes: 0
Reputation: 8206
String literals get interned by the CLR. Effectively meaning they will be created only once.
Upvotes: 2
Reputation: 85046
In your first example, it would only be available in the function. In your second it would be available to other functions in that same class.
Upvotes: 0