Extension methods are just static methods, that implement "instance methods", by taking a fake "this" pointer:
public static class Extensions
{
public static int ANewFakeInstanceMethod(this SomeObject instance, string someParam)
{
return 0;
}
}
You can still invoke it just like a static method - this is how the compiler compiles your code, anyhow:
var inst = new SomeObject();
int result1 = inst.ANewFakeInstanceMethod("str");
int result2 = Extensions.ANewFakeInstanceMethod(inst, "str");
If you can't get the extension method syntax, you can still use the 2nd syntax, even if you strip the this
from your static method definition:
var inst = new SomeObject();
int result2 = Extensions.ANewFakeInstanceMethod(inst, "str");
public static class Extensions
{
public static int ANewFakeInstanceMethod(SomeObject instance, string someParam)
{
return 0;
}
}
BUT
The syntax and usage you are trying to implement doesn't make sense. You're taking an existing DateTime
object instance (which has its own values for date and time), and trying to implement a new property/method off that instance that will return some unrelated constant.
Just use a static class, and define static read-only properties on it:
public static class KnownDates
{
public static DateTime StSpruffingsDay
{
get
{
return new DateTime(1, 2, 3, 4);
}
}
}
If this isn't a constant (as in, you need it for the current year), you should add a method that takes a year - not try to jam it into an extension method on top of a DateTime
, because DateTime
embodies more than just a year.
public static class KnownDates
{
public static DateTime GetTalkLikeAPirateDay(int year)
{
return new DateTime( // Todo: Calculate the value, based on Sept 19th
}
}
If you really need to get it relative to a DateTime
, it still makes your code more clear to pass it to the method:
var fiveMinutesAgo = DateTime.Now.AddMinutes(-5);
// ...
var arrrr = KnownDates.GetTalkLikeAPirateDay(fiveMinutesAgo.Year);
... Than it does to invoke it straight off a DateTime
instance:
var fiveMinutesAgo = DateTime.Now.AddMinutes(-5);
// ...
var arrrr = fiveMinutesAgo.GetTalkLikeAPirateDay();