1

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?

4
  • 1
    Purely a stylistic choice. No effect on performance. Commented Oct 29, 2012 at 18:32
  • 1
    Also, if you're unaware of it, when it comes to long string, the @ designator is invaluable. Commented Oct 29, 2012 at 18:33
  • Door number 3 is make it a public property. Commented Oct 29, 2012 at 18:34
  • 1
    Door number 4: make it a const within the method. Commented Oct 29, 2012 at 18:35

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

4 Comments

distinct string literals are only created once. Strings created at runtime are not (by default) interned.
In the OP's first example, would the LongString variable not reference the value in the intern table?
It would, and that's because it refers to a string literal in this case. My point is that, while interning certainly does apply here, it doesn't mean that every single string ever is always interned. In other situations you can have two different strings that aren't actually references to the same underlying char array.
@servy yes sorry, I do realise that but my answer was not thorough, thankyou for clarifying.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.