Visual Studio and Struct Debug Value of a Class

Consider the following simple program (using Visual Studio 2015):

public class Program { public static void Main(string[] args) { var dtClass = new MyDateTimeWrapperClass(DateTime.Today); var dtStruct = new MyDateTimeWrapperStruct(DateTime.Today); WriteLine(dtClass); WriteLine(dtStruct); ReadKey(); } } public class MyDateTimeWrapperClass { private readonly DateTime _value; public MyDateTimeWrapperClass(DateTime value) { _value = value; } public override string ToString() => _value.ToString("MM/dd/yyyy"); } public struct MyDateTimeWrapperStruct { private readonly DateTime _value; public MyDateTimeWrapperStruct(DateTime value) { _value = value; } public override string ToString() => _value.ToString("MM/dd/yyyy"); } 

The console will report the expected output of the ToString method. However, when in debug mode, the output file does not match.

enter image description here

I always thought that Visual Studio uses a ToString() call to display this value. But with the help of structures, this does not seem to be the case. Can anyone explain this behavior? I would appreciate answers that also describe how this value is calculated in the first place, as it seems that my understanding is incomplete.

Update: Additional Information

  • This problem does not occur when I use Visual Studio 2013.
  • Hard coding of ToString calls for different values ​​leads to normal behavior.
+5
source share
1 answer

Not sure about WHY - but you can use the DebuggerDisplayAttribute attribute for this effect:

https://msdn.microsoft.com/en-us/library/ms228992(v=vs.110).aspx <Guide to use https://msdn.microsoft.com/en-us/library/x810d419.aspx < Shows types that can be applied to

Something like this will work:

 [DebuggerDisplay("{ToString()}")] public struct MyDateTimeWrapperStruct { private readonly DateTime _value; public MyDateTimeWrapperStruct(DateTime value) { _value = value; } public override string ToString() => _value.ToString("MM/dd/yyyy"); } 

Use the following steps to remove quotes:

 [DebuggerDisplay("{ToString(),nq}")] 
+1
source

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


All Articles