views:

59

answers:

3

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?

+3  A: 

Nope - not possible

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

Rob Fonseca-Ensor
+2  A: 

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
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
SLC
OK, but then you are stripping a particular string, not ignoring the instance and generating something entirely different.
Hans Kesting
A: 

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

Perplexed
No, you couldn't do this as the existing DateTime class would also need to be declared partial.
Steven Mackenzie
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
@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
@Perplexed - 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