Override and Obsolete

time to read 7 min | 1218 words

I have recently created a grid that inherits from GridView, and add special processing. As part of the processing, I needed extra information about the data beyond just the list of items. I created a Bind() method that gets all the information, and handles the entire data binding scenario.

But this is not a common approach, and it is entirely possible that another developer will forget / not know that he needs to call this method  and use the following to add data to the grid:

grid.DataSource = foo;
grid.DataBind();

This would completely bypass my custom handling, and can lead to hard to discover bugs, after all, the code will look correct. In order to solve this issue, I used this approach:

[Obsolete("Use the Bind() method instead.", true)
public override object DataSource
{
    set
    {
        if(this.DesignMode==false)
    
       throw new InvalidOperationException(@"Can't use this setter.
                            You must use the Bind() method instead"
);
    }
}

I overrode just the setter for the DataSource property (something that I learned was possible only today), and added a compiler error when using this, as well as a runtime error. Both of those will direct the developer in the right path. I added the exception because the developer may call the class via is base class ,which will bypass the compiler obsolete error .

Update: Just to clarify, this is the Bind method, it does more than just

public void Bind<T>(ICollection<T> itemsToBind, ISecurable securable) { ... }

I added the bolded part to allow the control to work with the designer.