Search code examples
c#datetimeattributesconstants

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")]

Solution

  • 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;
        }
    }