Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime.Today and "static readonly"

Tags:

c#

.net

DateTime.Today is static readonly. So supposedly it should never change once (statically) instantiated.

However -- if I fire up an application and ask for the date at 11:59pm and then again at 12:01am, it will correctly give me different values each time i call it, right?

Let's say I wanted to create a static readonly "DateTime.TwoDaysFromNow" (just a representative example) that behaves the same way. .NET will tell me I can't b/c it's a readonly remember! How can I make it work?

Much appreciated, -Alan.

like image 813
Alan Avatar asked Feb 25 '11 19:02

Alan


People also ask

Is DateTime now static?

Now is a static property on the DateTime struct. By calling it, you get back a DateTime object, representing the current time in your computer, expressed as local time.

What is static readonly?

Static ReadOnly: A Static Readonly type variable's value can be assigned at runtime or assigned at compile time and changed at runtime. But this variable's value can only be changed in the static constructor. And cannot be changed further.

Are readonly variables static?

A readonly field can be initialized either at the time of declaration or within the constructor of the same class. Therefore, readonly fields can be used for run-time constants. Explicitly, you can specify a readonly field as static since like constant by default it is not static.

What is the difference between the static const and readonly keywords when applied to a type member?

The first, const, is initialized during compile-time and the latter, readonly, initialized is by the latest run-time. The second difference is that readonly can only be initialized at the class-level. Another important difference is that const variables can be referenced through "ClassName.


2 Answers

It's a static readonly property, not a static readonly field:

public static DateTime Today
{
    get
    {
        return Now.Date;
    }
}
like image 130
RQDQ Avatar answered Sep 24 '22 14:09

RQDQ


public static DateTime TwoDaysFromNow
{
    get { return DateTime.Today.AddDays(2); }
}

You can tell DateTime.Today is a property from Microsoft's Syntax of it:

public static DateTime Today { get; }

like image 26
Yuriy Faktorovich Avatar answered Sep 21 '22 14:09

Yuriy Faktorovich