Question

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

Was it helpful?

Solution

You can use the following:

var field = typeof(Pages).GetField("Home", BindingFlags.Public | BindingFlags.Static);
var value = (string)field.GetValue(null);

OTHER TIPS

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.

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.

As other have said, I'd avoid using reflection here. Also, although it adds a bit more code, an enum for the hardcoded page names is also a good idea (also suggested previously)

    public enum pages { LoggedOut, Login, Home }

    static Dictionary<pages, string> pageDict = new Dictionary<pages, string>() {
        {pages.Home, "Home.aspx"},
        {pages.Login, "Login.aspx"},
        {pages.LoggedOut, "LoggedOut.aspx"}
    };

    public static string getPage(pages pageName)
    {
        return pageDict[pageName];
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top