Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Struct and class display value in Visual Studio debug mode

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.

enter image description here

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.

Update: Additional Information

  1. This issue does not happen when I use Visual Studio 2013.
  2. Hardcoding the ToString calls to different values results in normal behavior.
like image 517
Will Ray Avatar asked Oct 19 '22 22:10

Will Ray


1 Answers

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}")]
like image 66
Chris Avatar answered Oct 21 '22 19:10

Chris