Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is DateTime.Now.Year an int and not a ushort

Tags:

.net

types

In the .Net framework DateTime structure, the Year is defined as an int (which is really A System.Int32). However, the MSDN documentation says that the value will always be between 1 and 9999. Thus, a ushort (System.UInt16) is more than adequate to store the value and takes up half the space. So why is it an int and not a ushort?

There is an implicit conversion from ushort to int so there is no casting that needs to be done to do integer arithmetic on the Year.

I realize this is a micro-optimization issue and thus not very important. I am just curious.

like image 246
epotter Avatar asked Jun 21 '12 14:06

epotter


1 Answers

Thus, a ushort (System.UInt16) is more than adequate to store the value and takes up half the space.

Where do you think that "space" is being wasted? DateTime doesn't store each component in a separate field anyway. If you're storing the year somewhere, feel free to cast it to a ushort - and cast Month to a byte, etc.

Note that ushort isn't CLS-compliant, which is probably the reason for it. There are a lot of properties which would make sense to be unsigned, such as string.Length etc... but the framework tries to be CLS-compliant where it can.

like image 99
Jon Skeet Avatar answered Jan 03 '23 14:01

Jon Skeet