When I’m making user controls for both Winforms and ASP.NET, I find myself writing the same section of code over and over again for each property on the form, which is this:
private string _url;
public string Url
{
get { return _url; }
set
{
if (_url == value)
return;
_url = value;
OnUrlChange(EventArgs.Empty);
}
}
public event EventHandler UrlChanged;
protected virtual void OnUrlChange(EventArgs e)
{
//Maybe add some extra logic here
if(UrlChanged != null)
UrlChanged(this, e);
}
Sometimes there’s the odd change. Maybe I’ll writing my own class that derives from EventArgs and use that.
This seems like it must be a common task. Maybe I’m doing it wrong and there’s a much easier way to write the lot? But if not, are there any custom refactoring tools that I can set up to fill in this code given the Property name Url?
Your pattern is pretty common, and is pretty much the best way to do this.
That being said, you should definitely use Visual Studio Snippets. They allow for easily creating templates for code like this. You can define your own placeholders, and when you insert the snippet, Visual Studio highlights the placeholders and allows you to tab through them.
I’d also recommend the Snippet Designer plugin, it will make snippet creation much easier and more fun. It also helps to find out snippet features that you didn’t know existed.