Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is datetime struct or class in C#? [closed]

Tags:

c#

datetime

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?

like image 314
Ozgur Erdogan Avatar asked Jan 09 '14 22:01

Ozgur Erdogan


2 Answers

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 : enter image description here

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.

like image 147
Pierre-Luc Pineault Avatar answered Nov 01 '22 17:11

Pierre-Luc Pineault


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.

like image 38
Sergey Kalinichenko Avatar answered Nov 01 '22 15:11

Sergey Kalinichenko