mattruma
mattruma

Reputation: 16677

How to you inspect or look for .NET attributes?

I have an enumeration for Status for a Task. Some of the statuses are considered obsolete, and I have marked them as obsolete, as seen below:

public enum TaskStatus
{
    [Description("")]
    NotSet = 0,
    Pending = 1,
    Ready = 2,
    Open = 3,
    Completed = 4,
    Closed = 5,
    [Description("On Hold")][Obsolete]
    OnHold = 6,
    [Obsolete]
    Canceled = 7
}

In my user interface I populate a drop down with values on the enumerations, but I want to ignore ones that are marked as obsolete. How would I got about doing this?

Upvotes: 1

Views: 748

Answers (3)

JoshBerke
JoshBerke

Reputation: 67068

Type enumType = typeof(testEnum);
enumType.GetFields(BindingFlags.Static | BindingFlags.GetField | BindingFlags.Public)[i].GetCustomAttributes(true);

Then you can use your choice of method to loop through the array and checking if there are any custom attributes.

Upvotes: 1

Cristian Libardo
Cristian Libardo

Reputation: 9248

You could write a LINQ-query:

var availableTaks = typeof (TaskStatus).GetFields(BindingFlags.Static | BindingFlags.GetField | BindingFlags.Public)
    .Where(f => f.GetCustomAttributes(typeof (ObsoleteAttribute), false).Length == 0);
foreach(var task in availableTaks)
    Console.WriteLine(task);

Upvotes: 3

masfenix
masfenix

Reputation: 7996

You can use the DebuggerHiddenAttribute and I know there is one that makes it hide from the properties explorer, but can't seem to remember the name.

Upvotes: 0

Related Questions