0

Say I write a switch statement where the return value is a string. Are the strings that this switch statements return interned (since they may be referenced many times)?

Say we have an enumeration called DogBreed.

private static string DogBreedToString(DogBreed dogBreed)
{
   return dogBreed switch
   {
       DogBreed.GoldenRetriever => "golden_retriever",
       _ => throw new InvalidOperationException($"Breed ({dogBreed}) is unsupported"),
   };
}

In other words, if this gets called two times from two different parts of the code, will both parts of the code receive a reference to the same instance of "golden_retriever"?

Tea
  • 160
  • 7
  • The compiler has an optimizer and the optimizer should merge the strings. A string is a class object which is difficult to merge. c# does not use pointers so depending where in the code the strings are located will determine if the strings get merged. – jdweng Jul 31 '22 at 02:12
  • 2
    Strings from literals are interned by default. Strings from `new String(someChars)` is not – Charlieface Jul 31 '22 at 02:23
  • 1
    Does this answer your question? [Why only literal strings saved in the intern pool by default?](https://stackoverflow.com/questions/8509035/why-only-literal-strings-saved-in-the-intern-pool-by-default) – Charlieface Jul 31 '22 at 02:25
  • 1
    If you're not sure if two strings were interned to the same memory location, you can always check them using [Reference.Equals](https://learn.microsoft.com/en-us/dotnet/api/system.object.referenceequals?view=net-6.0). – John Wu Jul 31 '22 at 02:52
  • For what it's worth, that's not A _switch statement_, it's a _switch expression_. Statements don't return anything – Flydog57 Jul 31 '22 at 05:19

0 Answers0