Constant DateTime in C#
I would like to put a constant date time in an attribute parameter, how do i make a constant datetime? It's related to a ValidationAttribute
of the EntLib Validation Application Block but applies to other attributes as well.
When I do this:
private DateTime _lowerbound = new DateTime(2011, 1, 1);
[DateTimeRangeValidator(_lowerbound)]
I'll get:
An object reference is required for the non-static field, method, or property _lowerbound
And by doing this
private const DateTime _lowerbound = new DateTime(2011, 1, 1);
[DateTimeRangeValidator(_lowerbound)]
I'll Get:
The type 'System.DateTime' cannot be declared const
Any ideas? Going this way is not preferable:
[DateTimeRangeValidator("01-01-2011")]
As some of the earlier responses note, a const DateTime
is not natively supported in C# and can't be used as an attribute parameter. Nevertheless, a readonly DateTime
(which is recommended over const
in Effective C#, 2nd edition [Item 2]) is a simple workaround for other situations as follows:
public class MyClass
{
public static readonly DateTime DefaultDate = new DateTime(1900,1,1);
}
The solution I've always read about is to either go the route of a string, or pass in the day/month/year as three separate parameters, as C# does not currently support a DateTime
literal value.
Here is a simple example that will let you pass in either three parameters of type int
, or a string
into the attribute:
public class SomeDateTimeAttribute : Attribute
{
private DateTime _date;
public SomeDateTimeAttribute(int year, int month, int day)
{
_date = new DateTime(year, month, day);
}
public SomeDateTimeAttribute(string date)
{
_date = DateTime.Parse(date);
}
public DateTime Date
{
get { return _date; }
}
public bool IsAfterToday()
{
return this.Date > DateTime.Today;
}
}
The DateTimeRangeValidator can take a string representation (ISO8601 format) as a parameter
e.g
LowerBound UpperBound
[DateTimeRangeValidator("2010-01-01T00:00:00", "2010-01-20T00:00:00")]
A single parameter will get interpreted as an UpperBound so you need 2 if you want to enter a LowerBound. Check the docs to see if there is a special 'do not care' value for UpperBound or if you need to set it to a very far future date.
Whoops, just re-read and noticed
'Going this way is not preferable'
[DateTimeRangeValidator("01-01-2011")]
Why not?
Would
private const string LowerBound = "2010-01-01T00:00:00";
private const string UpperBound = "2010-01-20T00:00:00";
[DateTimeRangeValidator(LowerBound, UpperBound)]
be any worse/different than (VB date literal format)
private const DateTime LowerBound = #01/01/2000 00:00 AM#;
private const DateTime UpperBound = #20/01/2000 11:59 PM#;
[DateTimeRangeValidator(LowerBound, UpperBound)]
hth,
Alan