Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is DateTime a structure in .Net?

Why is DateTime a structure instead of an inheritable class?

(I would like to be able to override the ToString() method but I can't.)

like image 207
Bastien Vandamme Avatar asked Oct 31 '09 13:10

Bastien Vandamme


People also ask

Is DateTime a struct C#?

DateTime is a struct . Which doesn't mean it can't have many different constructors and methods and overloads.

How does DateTime work in C#?

C# includes DateTime struct to work with dates and times. To work with date and time in C#, create an object of the DateTime struct using the new keyword. The following creates a DateTime object with the default value. The default and the lowest value of a DateTime object is January 1, 0001 00:00:00 (midnight).

What is DateTime type in C#?

We used the DateTime when there is a need to work with the dates and times in C#. We can format the date and time in different formats by the properties and methods of the DateTime./p> The value of the DateTime is between the 12:00:00 midnight, January 1 0001 and 11:59:59 PM, December 31, 9999 A.D.


2 Answers

Probably because it was seen as a small, simple and immutable data structure, much like an integer or decimal. Making it a struct under these conditions make using a DateTime very efficient. If it had been made a class, this efficiency benefit would have been lost because that would require memory allocations every time you create a new DateTime.

Besides, how many variant forms of a DateTime can you come up with? (Ignoring the allternate ToString implementations you have in mind.) It's not exactly a type that invites polymorphism.

Note that for using a different formatting strategy for your DateTimes, as I think you want, you'd better look at a different way to format than just using ToString. If you look at the ICustomFormatter interface in MSDN, you'll see how you can plug into the String.Format pipeline to override formatting without needing to subset an existing type.

like image 103
Ruben Avatar answered Sep 28 '22 02:09

Ruben


You can use Extension Methods for this: Declare extension:

public static class DateTimeExtensions
{
    public static string ToStringFormatted(this DateTime date)
    {
        return date.ToString("{d}");
    }
}

Use extension:

using DateTimeExtensions;
...
var d = new DateTime();
System.Diagnostics.Debug.WriteLine(d.ToStringFormatted());

This way you can simple implement your own method thats used on DateTime. This way it can easily be used everywhere within you solution. Only thing you have to do is using the namespace.

Ref: Extension Methods (c#)

like image 36
Ralf de Kleine Avatar answered Sep 28 '22 02:09

Ralf de Kleine