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.
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.
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.
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.
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.
It's a static readonly property, not a static readonly field:
public static DateTime Today
{
get
{
return Now.Date;
}
}
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With