Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using extension methods in [DebuggerDisplay] Attribute

The Attribute [DebuggerDisplay] (Using DebuggerDisplayAttribute) allows to define the display in the Debugger of VS 2010/2008. By modifying AutoExp.cs/.dll, I can even override the display of system types and 3rd party types, e.g.

[assembly: DebuggerDisplay (@"\{Name = {Name} FullName = {FullName}}", Target = typeof (Type))]

In the inner curly braces I can reference fields, properties and methods. Is it possible to reference extension methods ?

As an example, I tried to display shorter type names, e.g. $SCG.Dictionary instead of System.Collections.Generic.Dictionary. I added this to AutoExp.cs:

using DbgDisp;

[assembly: DebuggerDisplay (@"\{Name = {Name} ShortName = {ShortName()}}", Target = typeof (Type))]

namespace DbgDisp {
  public static class Ext {
    public static string ShortName (this Type t) { return string.Format ("[{0}]", t.Name); }
  } // Ext
} // DbgDisp

but the debugger complains: The name 'ShortName' does not exist in the current context.

Am I missing something, or is it just not possible to use extension methods there ?

I know I could override ToString (), but that helps only for my own types.

like image 207
MillKa Avatar asked Apr 09 '11 10:04

MillKa


2 Answers

Actually you can use extension methods passing this as the argument

[assembly: DebuggerDisplay(@"NetGuid = {ToString()} OracleGuid = {GuidExtensions.ToVarChar(this)}", Target = typeof(Guid))]
public static class GuidExtensions
{
    public static string ToVarChar(this Guid guid)
    {
        var newBytes = new byte[16];
        var oldBytes = guid.ToByteArray();
        for (var i = 8; i < 16; i++)
            newBytes[i] = oldBytes[i];

        newBytes[3] = oldBytes[0];
        newBytes[2] = oldBytes[1];
        newBytes[1] = oldBytes[2];
        newBytes[0] = oldBytes[3];
        newBytes[5] = oldBytes[4];
        newBytes[4] = oldBytes[5];
        newBytes[6] = oldBytes[7];
        newBytes[7] = oldBytes[6];

        return new Guid(newBytes).ToString("N").ToUpper();
    }    
}
like image 140
seesharper Avatar answered Nov 12 '22 08:11

seesharper


In short, no. For the same reasons that extension methods don't work with dynamic, which is that from just the method name, there is no way of knowing what using directives were in effect, and hence which extension methods are candidates. It is entirely possible to have scenarios where using different using directives changes the available methods, so there is no benefit in having it try to guess.

You'll have to limit yourself to regular methods, unless the string allows you to specify static methods on classes explicitly, i.e. DbgDisp.Ext.ShortName(foo).

like image 27
Marc Gravell Avatar answered Nov 12 '22 08:11

Marc Gravell