NibblyPig
NibblyPig

Reputation: 52922

Can you have an extension method on a type instead of on an instance of a type?

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?

Upvotes: 2

Views: 125

Answers (3)

Perplexed
Perplexed

Reputation: 123

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

Upvotes: 0

Hans Kesting
Hans Kesting

Reputation: 39255

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().

Upvotes: 2

Rob Fonseca-Ensor
Rob Fonseca-Ensor

Reputation: 15621

Nope - not possible

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

Upvotes: 3

Related Questions