Which forces enum.ToString () to set the member it represents

I studied the effects of calling .ToString() on enumeration elements - more specifically, whether it creates a new string object or not.

Consider the following definition of an enumeration:

 enum MyEnum { MyValue = 0, MyOtherValue = 1 } 

If I executed the following code with breakpoints on x , y and z and take a bunch of heaps at each point

 static void Main(string[] args) { Console.WriteLine(typeof(MyEnum)); var x = MyEnum.MyValue.ToString(); // Breakpoint 1 var y = MyEnum.MyValue.ToString(); // Breakpoint 2 var z = MyEnum.MyOtherValue.ToString(); // Breakpoint 3 Console.WriteLine(x, y, z); } 

I see the following results:

 | Stage | # string objects | |---------|------------------| | Initial | 463 | | BP 1 | 465 | | BP 2 | 465 | | BP 3 | 466 | 

I looked through enum.cs but could not find the reason (missing?) For the distributions.

  • What causes two distributions at the first breakpoint?
  • Why did the second call not cause the allocation? I don't see any searches in the string pool, and I don't expect these rename names to be interned, as they are retrieved by calling a virtual method that uses reflection to find it.
  • When I manually check the string values ​​of the heap in each picture, I see that step 1 adds "MyValue", step 2 adds nothing, and step 3 adds "MyOtherValue".

The general question is why Enum.ToString() seems to be putting the member that it represents. What part of the code causes internment?

+6
source share

Source: https://habr.com/ru/post/1013135/


All Articles