Tom Goff's .Net Musings

Tidbits of information regarding .Net, C#, and SQL Server.

COTW: DebuggerHiddenAttribute Class

leave a comment »

The DebuggerHiddenAttribute[^] allows you to “hide” constructors, properties, and methods (herein referred to as class members) from the debugger. This means that if a class member has this attribute applied, then the debugger will not allow the user to step into in that class member. In addition, the debugger will not honor any break points in that class member. There is an small exception to this last point which I will describe later.

In the following console application, I have two methods in addition to Main:

using System;
using System.Diagnostics;

namespace ConsoleApplication1 {
    class Program {
        static void Main(string[] args) {
            SomeMethod();
            SomeOtherMethod();
        }

        static void SomeMethod() {
            for (Int32 i = 0; i < 1000; i++)
                Console.WriteLine(i);
        }

        static void SomeOtherMethod() {
            for (Int32 i = 1000; i < 2000; i++)
                Console.WriteLine(i);
        }

    }
}&#91;/sourcecode&#93;If I set a break point on each method (as shown below) and start debugging the application, then Visual Studio will stop execution on each method as they are called.

<a href="https://tjoe.files.wordpress.com/2007/10/debuggerhiddenattribute_1.png" title="DebuggerHiddenAttribute 1"><img src="https://tjoe.files.wordpress.com/2007/10/debuggerhiddenattribute_1.png" alt="DebuggerHiddenAttribute 1" /></a>

Clearly, this is the expected behavior. Now if we apply the DebuggerHiddenAttribute to one of the methods as shown here:

using System;
using System.Diagnostics;

namespace ConsoleApplication1 {
    class Program {
        static void Main(string[] args) {
            SomeMethod();
            SomeOtherMethod();
        }

        [DebuggerHidden]
        static void SomeMethod() {
            for (Int32 i = 0; i < 1000; i++)
                Console.WriteLine(i);
        }

        static void SomeOtherMethod() {
            for (Int32 i = 1000; i < 2000; i++)
                Console.WriteLine(i);
        }

    }
}&#91;/sourcecode&#93;Now when debugging, Visual Studio will disable the associated break point because the method is "hidden". You can also see below the reason that Visual Studio gives for disabling the break point.

<a href="https://tjoe.files.wordpress.com/2007/10/debuggerhiddenattribute_2.png" title="DebuggerHiddenAttribute 2"><img src="https://tjoe.files.wordpress.com/2007/10/debuggerhiddenattribute_2.png" alt="DebuggerHiddenAttribute 2" /></a>

Using this attribute can make debugging a bit easier. Looking at the code below, assume we set a break point on the PrintMessage call in the Main method and then want to step into the PrintMessage. Without the DebuggerHiddenAttribute on the GetFormat method, we would first step into the GetFormat method. We would then have to step out of GetFormat, then step into PrintMessage. In this example, we know that GetFormat is defect free and would not provide any useful information if it was debugged. So we can safely apply the DebuggerHiddenAttribute.

using System;
using System.Diagnostics;

namespace ConsoleApplication1 {
    class Program {
        static void Main(string[] args) {
            PrintMessage(GetFormat(), "Hello World");
        }

        [DebuggerHidden]
        static String GetFormat() {
            return "MyApp: {0}";
        }

        static void PrintMessage(String format,
            params Object[] args) {
            Console.WriteLine(format, args);
        }
    }
}

When and where to use this attribute can be tricky. If there was a defect in GetFormat (assuming there was more substantial code there), then we would not be able to debug it without removing the DebuggerHiddenAttribute.

In the tool-tip above, Visual Studio implies that if ‘Just My Code’ was disabled then we would be able to step into class members that have the DebuggerHiddenAttribute. Although, in my tests this was not the case. With ‘Just My Code’ disabled, Visual Studio shows the break point as enabled, but it is never hit and I cannot step into the “hidden” method.

If we explicitly tell the debugger to break, using the Debugger.Break[^] method, then Visual Studio will show the call to the method as the current statement. So in the following code, the call to SomeMethod in Main will be highlighted as the current statement and the code after the Debugger.Break call will not be executed yet. If you continue execution, then the code following the Debugger.Break call will be executed.

using System;
using System.Diagnostics;

namespace ConsoleApplication1 {
    class Program {
        static void Main(string[] args) {
            SomeMethod();
            SomeOtherMethod();
        }

        [DebuggerHidden]
        static void SomeMethod() {
            for (Int32 i = 0; i < 1000; i++)                 Console.WriteLine(i);             Debugger.Break();             Console.WriteLine("Some code after the break");         }         static void SomeOtherMethod() {             for (Int32 i = 1000; i < 2000; i++)                 Console.WriteLine(i);         }     } }[/sourcecode]In essence, the code is stopped at the point we called Debugger.Break. Since Visual Studio will not step into the "hidden" method, it moves up the stack to the place where the "hidden" method was called and displays that to the developer. Using the attribute can make debugger easier, but it can also hide important information if it's not used correctly. In general, I have found that simple properties (e.g. ones that simply get or set a field) benefit from this attribute.

Advertisements

Written by Tom

October 31, 2007 at 9:52 am

TOTW: EventArgs.Empty

leave a comment »

Events in .Net should always have two parameters: sender and the event arguments. The first parameter is the object that generated the event. The second parameter is either an instance of EventArgs[^] or a class derived from EventArgs.

By using a class derived from EventArgs, developers can include additional information about the event. The following code, shows a typical event definition:

public class MyObject {
    // ... Other code ...

    /// <summary>
    /// This event is fired when something happens.
    /// </summary>
    [field: NonSerialized]
    public event EventHandler<MyCustomEventArgs> SomeEvent;

    /// <summary>
    /// This method is used to fire the <see cref="E:SomeEvent"/>
    /// event.
    /// </summary>
    /// <param name="sender">The sender.</param>
    /// <param name="e">The event arguments.</param>
    protected virtual void OnSomeEvent(Object sender,
        MyCustomEventArgs e) {
        if (null != SomeEvent)
            SomeEvent(sender, e);
    }
}

In the event above, I specify that the event will use MyCustomEventArgs (not shown). I can then include additional properties in MyCustomEventArgs as needed. There are times when no additional information can be or needs to be included with the event. In these cases, the event typically takes an instance of EventArgs. An example of this is shown here:

public class MyObject {
    // ... Other code ...

    /// <summary>
    /// This event is fired when something happens.
    /// </summary>
    [field: NonSerialized]
    public event EventHandler<EventArgs> SomeEvent;

    /// <summary>
    /// This method is used to fire the <see cref="E:SomeEvent"/>
    /// event.
    /// </summary>
    /// <param name="sender">The sender.</param>
    /// <param name="e">The event arguments.</param>
    protected virtual void OnSomeEvent(Object sender,
        EventArgs e) {
        if (null != SomeEvent)
            SomeEvent(sender, e);
    }
}

The following code shows an example of how to fire this event. In addition, it shows an overload of OnSomeEvent that provides the appropriate parameters.

public class MyObject {
    // ... Other code ...

    /// <summary>
    /// This method is used to do something important.
    /// </summary>
    public void SomeMethod() {
        // ... Other code ...

        OnSomeEvent(this, new EventArgs());

        // ... Other code ...
    }

    /// <summary>
    /// This method is used to fire the <see cref="E:SomeEvent"/>
    /// event.
    /// </summary>
    protected virtual void OnSomeEvent() {
        if (null != SomeEvent)
            SomeEvent(this, new EventArgs());
    }
}

The code above works great, but has one problem. Every time SomeEvent is fired, we allocate a new instance of EventArgs. Since EventArgs is immutable and has no properties or fields, we could allocate a single global instance of EventArgs and use that single instance every time we fire our event. Luckily, .Net already defines such an instance in EventArgs.Empty[^].

Using this new global instance of EventArgs, our code would look like this:

public class MyObject {
    // ... Other code ...

    /// <summary>
    /// This method is used to do something important.
    /// </summary>
    public void SomeMethod() {
        // ... Other code ...

        OnSomeEvent(this, EventArgs.Empty);

        // ... Other code ...
    }

    /// <summary>
    /// This method is used to fire the <see cref="E:SomeEvent"/>
    /// event.
    /// </summary>
    protected virtual void OnSomeEvent() {
        if (null != SomeEvent)
            SomeEvent(this, EventArgs.Empty);
    }
}

I put together a small sample project[^] to demonstrate the additional allocation. I also included a test of the Empty field from the String class. This is the code from the sample project:

static void Main(string[] args) {
List strings = new List(10000);
List eventArgs = new List(10000);
Int64 before, after;

Console.Write(“Starting \”\” test…”);
strings.Clear();
before = GC.GetTotalMemory(true);
for (Int32 i = 0; i < 10000; i++) strings.Add(""); after = GC.GetTotalMemory(true); Console.WriteLine("done ({0} bytes)", after - before); Console.Write("Starting String.Empty test..."); strings.Clear(); before = GC.GetTotalMemory(true); for (Int32 i = 0; i < 10000; i++) strings.Add(String.Empty); after = GC.GetTotalMemory(true); Console.WriteLine("done ({0} bytes)", after - before); Console.Write("Starting new EventArgs() test..."); eventArgs.Clear(); before = GC.GetTotalMemory(true); for (Int32 i = 0; i < 10000; i++) eventArgs.Add(new EventArgs()); after = GC.GetTotalMemory(true); Console.WriteLine("done ({0} bytes)", after - before); Console.Write("Starting EventArgs.Empty test..."); eventArgs.Clear(); before = GC.GetTotalMemory(true); for (Int32 i = 0; i < 10000; i++) eventArgs.Add(EventArgs.Empty); after = GC.GetTotalMemory(true); Console.WriteLine("done ({0} bytes)", after - before); Console.ReadKey(); }[/sourcecode]Note: I realize GC.GetTotalMemory isn’t the most accurate way to detect memory allocations.

And this is the output from one test run:

emptyfieldtest

As you can see, the only time the total memory is increased is when we create new instances of EventArgs (as expected). Strings have special handling in .Net, such as string interning[^], but there is no special handling for EventArgs. This means you have to specifically use the EventArgs.Empty field.

You won’t see a huge improvement, if any, by using EventArgs.Empty. This is just a good coding practice.

Written by Tom

October 23, 2007 at 8:02 am

COTW: DebuggerBrowsableAttribute Class

with one comment

The DebuggerBrowsableAttribute[^] class allows you to specify which fields and properties of your classes will be displayed in the debugger view (e.g. Visual Studio’s Watch windows). The following code samples and screen-shots will illustrate how to use this attribute.

Note: This attribute is not currently supported in Visual Basic.

There are three possible settings that can be used with this attribute and they are defined by the DebuggerBrowsableState[^] enumeration. The first option is Collapsed, which is the default value if the DebuggerBrowsableAttribute is not specified. In the following class, neither the field nor the property have this attribute specified. This means it will use the Collapsed option.

public class MyClass {
    /// <summary>
    /// Initializes a new instance of the
    /// <see cref="MyClass"/> class.
    /// </summary>
    public MyClass() {
        this.items = new List<String>();
        this.items.Add("One");
        this.items.Add("Two");
        this.items.Add("Three");
    }

    /// <summary>
    /// Holds the items.
    /// </summary>
    private List<String> items;

    /// <summary>
    /// Gets or sets the items.
    /// </summary>
    /// <value>The items.</value>
    public List<String> Items {
        get {
            return this.items;
        }
        set {
            this.items = value;
        }
    }
}

When viewing an instance of this class in Visual Studio’s watch window, it will appear as shown here:

DebuggerBrowsableAttribute_Collapsed

The next option is called Never and will remove the associated field or property from the debugger’s view. In the following code, we have indicated that we do not want the debugger to display the Items property:

public class MyClass {
    /// <summary>
    /// Initializes a new instance of the
    /// <see cref="MyClass"/> class.
    /// </summary>
    public MyClass() {
        this.items = new List<String>();
        this.items.Add("One");
        this.items.Add("Two");
        this.items.Add("Three");
    }

    /// <summary>
    /// Holds the items.
    /// </summary>
    private List<String> items;

    /// <summary>
    /// Gets or sets the items.
    /// </summary>
    /// <value>The items.</value>
    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
    public List<String> Items {
        get {
            return this.items;
        }
        set {
            this.items = value;
        }
    }
}

As you can see below, the Items property is no longer shown in the watch window:

DebuggerBrowsableAttribute_Never

The final option is called RootHidden and is only useful for fields or properties that are collections or arrays. If this option is used for items that are not a collection or an array, then it will be hidden from the debugger’s view. The screen-shot below illustrates how our class would be displayed if we specified the RootHidden option for the Items property.

DebuggerBrowsableAttribute_RootHidden

As you can see, the entries that would typically be found below the Items property (by expanding the plus sign) are now merged with the other MyClass fields and properties. The RootHidden option is useful if you are writing a class that wraps a collection or array. When viewing such a class in the debugger, then you would typically drill down to the collection or array. Using this option would save you that additional step when debugging.

If you are developing .Net classes or controls for use by other developers, then you should consider using the Never option to hide private and internal fields and properties. Since the consumers of your .Net assemblies would not be able to access or modify private or internal members, then typically they would not need to see them in the debugger. Of course, there are always exceptions.

Keep in mind that these attributes are just recommendations of how you think your class should be shown in the debugger. The debugger does not have to follow them. In Visual Studio, you can choose to ignore this (and other similar) attributes by checking the configuration option shown below.

DebuggerBrowsableAttribute_VS

As with last week, this article[^] is a great resource for further reading on this subject.

Written by Tom

October 23, 2007 at 7:17 am

TOTW: Google ‘site’ keyword

leave a comment »

While not specifically related to the topics covered by my blog, I do find the following to be invaluable. When searching for information on a given .Net class (or whatever), sometimes the results are cluttered with irrelevant links. To reduce the clutter, I will often use the “site” keyword in my Google searches.

For example, if we search Google for DebuggerDisplayAttribute[^] then we get a little over 1000 hits. We can specify our search expression as “DebuggerDisplayAttribute site:wordpress.com” to limit the results from the wordpress.com site as shown here[^].

 Google has many[^] more search criteria that you can specify, all of which can help you find what you need. Most other search engines will have similar options, but I tend to use Google.

Written by Tom

October 16, 2007 at 8:33 am

Posted in Tip of the Week

COTW: DebuggerDisplayAttribute Class

leave a comment »

The DebuggerDisplayAttribute[^] class allows you to specify how your classes will be displayed in a debugger. Specifically, you can define a string format that uses properties or fields from your class. This string will then be used by the debugger when it displays debug information about your class (e.g. in the Watch windows of Visual Studio).

MSDN[^] has a good write up on how to use this attribute. In the class below I have specified a string format that includes the Name property:

[DebuggerDisplay("The name of MyClass is {Name}")]
public class MyClass {
    /// <summary>
    /// Initializes a new instance of the
    /// <see cref="MyClass"/> class.
    /// </summary>
    /// <param name="name">The name.</param>
    public MyClass(String name) {
        this.name = name;
    }
 
    /// <summary>
    /// Holds the name.
    /// </summary>
    private String name;
 
    /// <summary>
    /// Gets or sets the name.
    /// </summary>
    /// <value>The name.</value>
    public String Name {
        get {
            return this.name;
        }
        set {
            this.name = value;
        }
    }
}

Assuming that I create a new instance of MyClass and pass the string “Test1” into the constructor, then Visual Studio will display this object like this:

DebuggerDisplayAttribute (1)

If you find that you often drill down in the Watch window to view a few properties of your classes, then you may want to use this attribute. If you are designing reusable classes or components, then you should definitely consider using this attribute. For further reading on this subject, this article[^] is a great resource.

Written by Tom

October 16, 2007 at 8:11 am

TOTW: Visual Studio’s Shortcuts

leave a comment »

Visual Studio has a lot of functionality, some of which is mostly unknown. It’s hard to present all the functionality Visual Studio has to offer without overwhelming the user. Therefore, most commands are not visible through the menu or toolbars. However, there are many more commands tied to keyboard short-cuts.

We are all familiar with keyboard short-cuts which use a single key along with a combination of the Control, Alt, and/or Shift keys. Some examples of these types of short-cuts include Ctrl+C for copy, Ctrl+X for cut, etc. Visual Studio 2005 introduced key chords, which are multiple keys typed while holding down the Control key. For example, if you select some code then press and hold the Control key and type K+C, then the selected code will be commented out. These key chords allow a single key, such as C, to be used for various commands. In addition, the first key of the chord can be used to group similiar commands. For example, Ctrl+K+U will uncomment the selected text.

I’d recommend learning the short-cuts for commands you use frequently. If a command you use alot does not already have a short-cut, then I’d recommend assigning one. Microsoft as alot of information on this subject, but I’ve included some links to get you started:

Written by Tom

October 7, 2007 at 10:12 pm

COTW: EventHandler Generic Delegate

leave a comment »

The EventHandler Generic Delegate[^] allows developers to easily define events without having to define a custom delegate. In the following code, MyObject defines an event which uses a custom class derived from EventArgs[^]:

public class MyObject {
    // ... Other code ...

    /// <summary>
    /// This is a custom delegate for use with the
    /// <see cref="E:SomeEvent"/> event.
    /// </summary>
    /// <param name="sender">The sender.</param>
    /// <param name="e">The event arguments.</param>
    public delegate void SomeEventHandler(Object sender,
        MyCustomEventArgs e);

    /// <summary>
    /// This event is fired when something happens.
    /// </summary>
    [field: NonSerialized]
    public event SomeEventHandler SomeEvent;

    /// <summary>
    /// This method is used to fire the <see cref="E:SomeEvent"/>
    /// event.
    /// </summary>
    /// <param name="sender">The sender.</param>
    /// <param name="e">The event arguments.</param>
    protected virtual void OnSomeEvent(Object sender,
        MyCustomEventArgs e) {
        if (null != SomeEvent)
            SomeEvent(sender, e);
    }
}

public class MyCustomEventArgs : EventArgs {
    /// <summary>
    /// Initializes a new instance of the
    /// <see cref="MyCustomEventArgs"/> class.
    /// </summary>
    /// <param name="whatHappened">What happened.</param>
    public MyCustomEventArgs(String whatHappened) {
        this.whatHappened = whatHappened;
    }

    /// <summary>
    /// Holds a string that tells what happened.
    /// </summary>
    private String whatHappened;

    /// <summary>
    /// Gets a string that tells what happened.
    /// </summary>
    /// <value>What happened.</value>
    public String WhatHappened {
        get {
            return this.whatHappened;
        }
    }
}

This is a typical setup for events and is the only way to define events in .Net 1.x. However in .Net 2.0 the generic EventHandler can be used to forgo the definition of the delegate. In the following code, we have removed the custom delegate and replaced it with the generic EventHandler (the class MyCustomEventArgs is exluded from the code below because it is unchanged from the previous example):

public class MyObject {
    // ... Other code ...

    /// <summary>
    /// This event is fired when something happens.
    /// </summary>
    [field: NonSerialized]
    public event EventHandler<MyCustomEventArgs> SomeEvent;

    /// <summary>
    /// This method is used to fire the <see cref="E:SomeEvent"/>
    /// event.
    /// </summary>
    /// <param name="sender">The sender.</param>
    /// <param name="e">The event arguments.</param>
    protected virtual void OnSomeEvent(Object sender,
        MyCustomEventArgs e) {
        if (null != SomeEvent)
            SomeEvent(sender, e);
    }
}

As you can see, the EventHandler generic delegate saves us from having to define custom delegates everytime we define a new custom EventArgs class.

Written by Tom

October 7, 2007 at 8:33 pm

Posted in .Net, C#, Class of the Week