Saturday, August 05, 2006

One-Liners Getters And Setters For ASP.Net Control Properties


It is a little tiring to repeat the same code when persisting properties in the ViewState.
You basically have to do this for each property. Let assume we have a Count and a Text property.

int Count
{
    get
    {
        if(ViewState["Count"] == null) return 0; // Handle the null case
        return (int) ViewState["Count"]; // Need to cast
    }
    set
    {
        ViewState["Count"] = value;
    }
}

string Text
{
    get
    {
        if(ViewState["Text"] == null) return string.Empty; // Handle the null case
        return (string) ViewState["Text"];// Need to cast
    }
    set
    {
        ViewState["Text"] = value;
    }
}

Each time, you have to handle the case where the slot in ViewState is null and decide on a default value. It gets very boring very quickly. Casting the return value gets tiring too.

In my day job (yes, I have one), we have made our own bases classes for UserControls. This allows us to use some goodies we have made over time that is relevant to our application.

It would be cool to somehow "Factorize" this .... so here it is. We use generics to do the same logic every time.

namespace Developmentor
{
    public class UserControl : System.Web.UI.UserControl
    {
        protected void SetProperty<T>(string Name, T value)
        {
            ViewState[Name] = value;
        }

        protected T GetProperty<T>(string Name, T defaultValue)
        {
            if (ViewState[Name] == null)
            {
                return defaultValue;
            }
            return (T)ViewState[Name];
        }
    }
}

Now use it in an ascx like this. Just change the Inherits to point to your new and improved base. We have gained a little. At least we can do all this in one line now. There is still some typing but it is a little more 'Generic' ;-)


<%@ Control Language="C#" ClassName="simpleControl" Inherits="Developmentor.UserControl" %>

<script runat="server">
    
    string TheProperty
    {
        set
        {
            SetProperty<string>("TheProperty", value);
        }
        get
        {
            return GetProperty<string>("TheProperty", "?");
        }
    }
    protected override void Render(HtmlTextWriter writer)
    {
        writer.Write(TheProperty);
    }
</script>

This has been in my mind for a while. If you think that a brain like mine can't come up with this, well, you are right. I saw this in the Atlas framework using Reflector. Somebody at microsoft is thinking. When can we get this in the System.Web.UI.Control class in the framework? .Net 3.0?


Groups are talking. We´re listening. Check out the handy changes to Yahoo! Groups.

No comments: