首页 > 解决方案 > Visual Studio: [DebuggerDisplay], shows "not a valid format specifier" when specifying format

问题描述

If I specify a (date) format on the [DebuggerDisplay], I see a error CS0726:

error CS0726: ':d' is not a valid format specifier

For example this code:

[DebuggerDisplay("{From:d} - {To:d}")
public class DateRange 
{
    public DateTime From { get; set; }
    public DateTime To { get; set; }
}

Shows when debugging in Visual Studio:

enter image description here

标签: c#visual-studiovisual-studio-2017debuggerdisplay

解决方案


For specifying the format on the [DebuggerDisplay] you need an expression, e.g. ToString("d") - and escape the quotes.

This works:

[DebuggerDisplay("{From.ToString(\"d\"),nq} - {To.ToString(\"d\"),nq}")
public class DateRange 
{
    public DateTime From { get; set; }
    public DateTime To { get; set; }
}

I also added a ,nq so we don't render extra quotes.

See Using Expressions in DebuggerDisplay

Result:

enter image description here

Note: ,d won't work for specifying the format - It won't give an error but I also won't change the format


推荐阅读