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
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.
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.
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.
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...
}
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