user192936
user192936

Reputation:

Proper way for string literals

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

Answers (3)

MattDavey
MattDavey

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

Vitaliy
Vitaliy

Reputation: 8206

String literals get interned by the CLR. Effectively meaning they will be created only once.

Upvotes: 2

Abe Miessler
Abe Miessler

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

Related Questions