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 is not the same.
I had always thought that Visual Studio used a ToString()
call to display this value. Yet with structs this appears to not be the case. Could someone explain this behavior? I would appreciate answers which also describe how this value is computed in the first place, as it seems my understanding is incomplete.
ToString
calls to different values results in normal behavior.Not sure about WHY - but the DebuggerDisplayAttribute could be used for that effect:
https://msdn.microsoft.com/en-us/library/ms228992(v=vs.110).aspx < Guide to using https://msdn.microsoft.com/en-us/library/x810d419.aspx < Shows types it can be applied to
Something like this would 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 follow to remove quotes:
[DebuggerDisplay("{ToString(),nq}")]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With