I just started c#. But can not figure out DateTime
. I know it is a struct but why do I see different ways of initialize it like class sometime.
How is this if it is a struct?
DateTime myValue = DateTime.Now; // This is struct
DateTime myValue2 = new DateTime(); // This is class with +11 overloads.
So is there two versions of datetime in c# one is struct and other is class?
It is indeed a structure. To know which type is something, you can do two things :
1) Look at the doc, for DateTime it is clearly indicated in the title
2) Hover over the type. Visual Studio will pop a tooltip :
Structs behave mostly like classes, you can instantiate them with the new
operator and they can have methods too. You cannot use the way they are instantiated as a way to tell if something is struct or a class.
A type cannot be a struct
and a by-reference type at the same time. Both constructs make a DateTime
, which is a value type (also known as the struct
).
The difference between the two is that the first produces the value to be copied inside a static property called Now
, and the second initializes the value through one of DateTime
's 11 constructors.
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