I am trying to use an extension method to initialize a datetimepicker control to being on the previous work day from today. However this is causing my form design window to show an error as it cannot find the extension method.
You can quickly replicate this error by creting a new windows form, adding a datetimepicker. Then create the following new class to extend DateTime to add a NextDay() method:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ExtensionMethodDesignWindowTest
{
public static class DateTimeExtensions
{
public static DateTime NextDay(this DateTime date)
{
return date.AddDays(1);
}
}
}
And finally in Form1.designer.cs add the line
this.dateTimePicker1.Value = DateTime.Today.NextDay();
under the datetimepicker1 section.
(edit: and also using.system; at the top)
When you navigate back to the form design window you should see the error. Note that this code builds fine and runs correctly, with the datetimepicker showing tomorrow’s date when the form loads. Also if you replace the added line in Form1.designer.cs with
this.dateTimePicker1.Value = DateTime.Today.AddDays(1);
Then you do not get the error in the design window. This makes me assume that the error is because the windows form design window can’t see the ExtensionMethodDesignWindowTest namespace.
How can I make the form design window be able to see my extension methods?
Thanks
Dan
btw though I doubt it matters here is some IDE version info for what I’m using:
Microsoft Visual Studio 2010
Version 10.0.30319.1 RTMRel
Microsoft .NET Framework
Version 4.0.30319 RTMRel
Generally it’s bad practice to put your own code in the designer – VS may regenerate the designer code and then you’d lose your changes.
You should be able to invoke your extension method from eg Form_Load ie