views:

204

answers:

3

I've got the following class:

public static class Pages
{
    public static string LoggedOut = "LoggedOut.aspx";
    public static string Login = "Login.aspx";
    public static string Home = "Home.aspx";
}

I know I can use Pages.Home statically, but there is a reason for my question.

I wish to have a method that I can call like this:

string pageName = Pages.GetPage("Home");

etc.

C'est possible?

Thanks, Dave

+6  A: 

You can use the following:

var field = typeof(Pages).GetField("Home", BindingFlags.Public | BindingFlags.Static);
var value = (string)field.GetValue(null);
Konrad Rudolph
thanks, that's perfect.
A: 

Just my tuppence... if you are going to use literals ("Home"), then I would absolutely bind to the const, i.e. Pages.Home (they should probably be constants in the example given). The reflection approach might be handy if you have:

string s = ...something clever...
string page = GetPage(s);

If you do switch to const, then note that they manifest as static fields:

string s = ...something clever...
FieldInfo field = typeof(Pages).GetField(s,
     BindingFlags.Static | BindingFlags.Public);
string page = (string)field.GetValue(null);

If it is used heavily you could also cache these in a dictionary.

Marc Gravell
+3  A: 

You can do it like Konrad suggested using reflection. But I would consider it much better design to use a dictionary and not rely on reflection for such a task.

public static class Pages
{
    private static readonly IDictionary<String, String> PageMap = null;

    private static Pages()
    {
        Pages.PageMap = new Dictionary<String, String>();

        Pages.PageMap.Add("LoggedOut", "LoggedOut.aspx");
        Pages.PageMap.Add("Login", "Login.aspx");
        Pages.PageMap.Add("Home", "Home.aspx");
    }

    public static GetPage(String pageCode)
    {
        String page;
        if (Pages.PageMap.TryGet(pageCode, out page)
        {
            return page;
        }
        else
        {
            throw new ArgumentException("Page code not found.");
        }
    }
}

You should of course adjust the error handling to your actual requirements.

Daniel Brückner
since his original class hard-coded the three page properties, then he could use an enum of those values as keys in the Pages dictionary. helps avoid typos.
Mike Jacobs
Good point if the page collection is static (as the original code suggests).
Daniel Brückner