I am wondering if I can use extension method or other techniques to extend static class like
System.Net.Mime.MediaTypeNames.Image
, it has fewer type than I need.

- 39,603
- 20
- 94
- 123

- 83,087
- 147
- 309
- 426
-
You can't extend static classes; search SO for duplicates of this question and you'll see some workarounds. – BeemerGuy Nov 19 '10 at 01:39
-
Why would you ever need that? Static class has no context, and whatever you can inside a static class could be done "anywhere" else in the code. – Manish Basantani Nov 19 '10 at 07:42
-
@Amby - I think you might want to do it solely for organizational puropses. Sure you could create a static ImageUtility class with the necessary methods (which, according to this answer he will have to do anyhow), but I think the OP would like to organize his code in a way that he doesn't need the additional class. Unfortunately, you can't. (I came here looking to do the same). – MattW Aug 06 '12 at 13:52
-
@ManishBasantani It would be great to be able to extend a static class in this way. What if you could add extension methods to `Math`, for example? That would be way better than having multiple `MathHelper` classes all over the place. – Dave Cousineau Jul 27 '14 at 22:58
2 Answers
No, extension methods can only be used to add instance methods, not static methods (or even properties). Extension methods are really just syntactic sugar around static methods. For instance, when you use an extension method such as Count():
var list = GetList();
var size = list.Count();
This is actually compiled to:
var list = GetList();
var size = Enumerable.Count(list);
You can't add additional static methods to an existing class using extension methods.

- 11,549
- 40
- 44
-
Is it correct to say that "extension methods can only be used to add instance methods"? As you explain, they only give the appearance of being instance methods. They are not actually instance methods, or you would be able to access non-public members of the class. – Dave Cousineau Jul 27 '14 at 23:01
No, this is not yet possible in C#, though hopefully it will become so at some point. And you can't subclass a static class and add new methods that way, since static classes must derive from object
. One thing you can do though, which produces a pretty similar effect in your code, is simply declare another static class that you will use instead when you want your extension methods. For example:
public static class MessageBox2
{
public static DialogResult ShowError(string Caption, string Message, params object[] OptionalFormatArgs)
{
return MessageBox.Show(string.Format(Message, OptionalFormatArgs), Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Since the original class is static, by definition the "extension" method doesn't need to receive an instance as a this
parameter, and can simply use static methods of the original class.

- 6,719
- 1
- 35
- 46