Saturday, July 30, 2016

C#: EditorBrowsabilityAttribute and hiding Methods, Properties and Field from IntelliSense

The .NET Framework includes the System.ComponentModel namespace's EditorBrowsableAttribute which allows the programmable elements to be used in an application but to be hidden from IntelliSense. Why expose a method (or any programmable element) as public but hide it from IntelliSense? If the method has been deprecated then it makes sense to allow it to be used in applications but at the same time to hide it from developers. When the method does not show up in IntelliSense courtesy of EditorBrowsableAttribute, the method is less likely to be used by developers when writing applications.

An example of a class garnishing programmable elements with the EditorBrowsableAttribute attribute is as follows:

using System.ComponentModel;

namespace AnyAssembly
    public class PoliticsAreBoring
        public static short DonaldTrump { get; set; }

        public static short HillaryClinton { get; set; }

        public static long AlanTuring { get; set; }

        public static long AdmiralGraceHopper { get; set; }

The properties DonaldTrump and HillaryClinton of the PoliticsAreBoring class are decorate with the EditorBrowsableAttribute attribute. The value of EditorBrowsableState.Never is passed to the constructor of EditorBrowsableAttribute. When the class, PoliticsAreBoring, is referenced by another application the IntelliSense for PoliticsAreBoring are as follows:

Notice in the previous screenshot that the properties DonaldTrump and HillaryClinton are not listed by IntelliSense even though they are public static members of their class.. The PoliticsAreBoring class resides in the AnyAssembly.dll assembly. In order for IntelliSense not to see properties decorated with [EditorBrowsable(EditorBrowsableState.Never)] the assembly must not be part of a project in the current solution. In the screenshot below, AnyAssembly.dll is a file residing on disk and is not a project in the solution: 

If the AnyAssembly project is added to the solution, IntelliSense show the properties decorated with [EditorBrowsable(EditorBrowsableState.Never)]. An example of this is as follows:

IntelliSense shows all the properties which is convenient when developing the AnyAssembly assembly. When the assembly is used without a project (say released as an SDK) then all programmable entities decorated with [EditorBrowsable(EditorBrowsableState.Never)] are not visible but can be used if simply typed into the source code. 

The EditorBrowsableAttribute attribute can be used to decorate classes, structures, constructors, fields, methods, properties, events, etc. 

1 comment :