Constant DateTime in C#

Viewed 73219

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

DateTime types can never be a constant in C#.

write a method like:

private static DateTime? ToDateTime(string value)
    {
        if (string.IsNullOrWhiteSpace(value))
        {
            return null;
        }

        return DateTime.ParseExact(value, "dd-MM-yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None);
    }

Now you can use strings in datarow like: [null, "28-02-2021", "01-03-2021", 3)]

Old question, but here's another solution:

 public DateTime SOME_DATE
 {
      get
      {
           return new Date(2020, 04, 03);
      }
      set
      {
           throw new ReadOnlyException();
      }
 }

The main advantage of this solution is that it allows you to store the date in a DateTime, not having to use strings. You can also not throw any exception and just do nothing on set if you want.

Related