What Was I Thinking?

Follies & Foils of .NET Development
posts - 95 , comments - 352 , trackbacks - 0

My Links



Post Categories

Check These Out


Iterating Static Fields / Properties

Often during development I end up with "Constants" classes, classes of constant or static values that I want design time Visual Studio intellisense support for, and run-time domain checking.

Consider the following class:

public static classConstants
       public static classClaimTypes
           internal static stringClaimTypeNameSpace = "http://schemas.wtfsolutions.com/2008/07/claims/profile/";
           public static stringFirstName = ClaimTypeNameSpace + "firstname";
           public static stringLastName = ClaimTypeNameSpace + "lastname";
           public static stringDateOfBirth = ClaimTypeNameSpace + "dateofbirth";
           public static stringFavoriteColor = ClaimTypeNameSpace + "favoritecolor";



This class is handy at design time.  When I type "Constants.ClaimTypes." up pops an intellisense list of the valid claim types for my application.

The problem with this list is that you can't iterate through it at runtime, ensuring the value of a variable is in the valid ClaimType domain of values.  Ideally I'd like to be able to do this: ** THIS DOES NOT WORK ***

private bool validateClaimType(string claimType)
    return Constants.ClaimTypes.Contains(claimType);

Fortunately, we can use reflection to build a runtime dictionary of the field name and field values

private Dictionary<string, string> staticFieldsToList(Type targetType)
    var list = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
    var fields = targetType.GetFields(BindingFlags.Public | BindingFlags.Static);
    foreach (var field in fields)
        list.Add(field.Name, field.GetValue(null) as string);
    return list;

and validate our claim type as follows: ** THIS WORKS **

private bool validateClaimType(string claimType)
    return staticFieldsToList(typeof(Constants.ClaimTypes)).ContainsValue(claimType);

In my real application I store the dictionary to a static field to avoid multiple reflection-based calls, but for the purposes of demonstrating functionality, the above code reflects the static class each call.


The best of both worlds, design-time IDE support and run-time domain validation. 

I love it when a plan comes together.

Print | posted on Wednesday, July 9, 2008 10:27 PM | Filed Under [ Visual Studio ]


No comments posted yet.
Post A Comment

Powered by: