2

I can have an extension method like this:

DateTime d = new DateTime();
d = d.GetRandomDate();

GetRandomDate is my extension method. However the above doesn't make much sense. What would be better is:

DateTime d = DateTime.GetRandomDate();

However, I don't know how to do this. An extension method created as:

public static DateTime GetRandomDate(this System.DateTime dt)

will only add the GetRandomDate() in the first example above, not the second one. Is there a way to achieve the desired behaviour?

NibblyPig
  • 51,118
  • 72
  • 200
  • 356

3 Answers3

3

Nope - not possible

You'll need to access the method on your own static class...

Rob Fonseca-Ensor
  • 15,510
  • 44
  • 57
2

Why would you want to? If you want to call a static method, why not call it directly?

OK, you will need to use something like DateTimeHelper.GetRandomDate() instead of DateTime.GetRandomDate().

Hans Kesting
  • 38,117
  • 9
  • 79
  • 111
  • As for why, the same reason you don't call MyStringHelper.StripSpaces(myString) instead of using an extension method like string s = "a b c"; s.StripSpaces(); - convenience – NibblyPig Apr 23 '10 at 08:43
  • OK, but then you are stripping a particular string, not ignoring the instance and generating something entirely different. – Hans Kesting Apr 23 '10 at 09:54
0

Just throwing this out there, but could you create a partial static class of datetime and throw the extension method on that?

Perplexed
  • 123
  • 7
  • No, you couldn't do this as the existing DateTime class would also need to be declared partial. – Steven Mackenzie Apr 23 '10 at 15:56
  • No, I'm pretty sure partial classes are a compiler feature, not a CLR feature, so even if DateTime was partial it would not work, because you cannot have part of a class in one assembly and part of it in a different assembly. – Qwertie Apr 23 '10 at 16:10
  • @Qwertie - but can't you just put it in the System namespace? (of course, it's not recompiling the System namespace upon pushing the big green button) @Steven - you're right - I just tried it in code myself and that's not going to fly. – Perplexed Apr 23 '10 at 16:10
  • sure you can declare a System.DateTime, but it would be a completely separate class. Probably the compiler would give an error when you try to use System.DateTime because it doesn't know which one you are referring to. – Qwertie Apr 26 '10 at 15:51