Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I write a "fluent" datetime value?

Tags:

c#

datetime

How do I Write C# code that will allow to compile the following code :

var date = 8.September(2013); // Generates a DateTime for the 8th of September 2013
like image 551
jim finegan Avatar asked Jun 20 '13 21:06

jim finegan


People also ask

Is DateTime a value type?

The DateTime value type represents dates and times with values ranging from 00:00:00 (midnight), January 1, 0001 Anno Domini (Common Era) through 11:59:59 P.M., December 31, 9999 A.D. (C.E.) in the Gregorian calendar.

What is default value of DateTime in C#?

The default and the lowest value of a DateTime object is January 1, 0001 00:00:00 (midnight). The maximum value can be December 31, 9999 11:59:59 P.M. Use different constructors of the DateTime struct to assign an initial value to a DateTime object.


2 Answers

You can use an extension method:

public static class MyExtensions
{
    public static DateTime September(this int day, int year)
    {
        return new DateTime(year, 9, day);
    }
}

However, this is generally bad practice, and I'd recommend against this kind of thing, especially for something as trivial as this—is new DateTime(2013, 9, 8) really so much more difficult than 8.September(2013)? There may be times where this kind of trick can be useful or fun for practice, but it should be used sparingly.

like image 81
p.s.w.g Avatar answered Nov 01 '22 06:11

p.s.w.g


I would recommend against this, as it strikes me as very poor style. That said, if you really want to do this statically, you would need to define twelve different extension methods (one for each month name) like so:

public static class DateConstructionExtensions
{
    public static DateTime January(this int day, int year)
    {
        return new DateTime(year, /* month: */1, day);
    }

    // equivalent methods for February, March, etc...
}
like image 21
Mike Strobel Avatar answered Nov 01 '22 06:11

Mike Strobel