Constant DateTime in C#

C#DatetimeAttributesConstants

C# Problem Overview


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

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

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

Solution 3 - C#

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

Solution 4 - 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)]

Solution 5 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBernoulli ITView Question on Stackoverflow
Solution 1 - C#JonathanView Answer on Stackoverflow
Solution 2 - C#Jerad RoseView Answer on Stackoverflow
Solution 3 - C#AlanTView Answer on Stackoverflow
Solution 4 - C#Michael de VosView Answer on Stackoverflow
Solution 5 - C#CR0N0S.LXIIIView Answer on Stackoverflow