Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extension method to extend static class [duplicate]

Tags:

c#

.net

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.

like image 475
user496949 Avatar asked Nov 19 '10 01:11

user496949


People also ask

Can extension methods only extend static classes?

An extension method must be a static method. An extension method must be inside a static class -- the class can have any name. The parameter in an extension method should always have the "this" keyword preceding the type on which the method needs to be called.

What is the difference between a static method and an extension method?

The only difference between a regular static method and an extension method is that the first parameter of the extension method specifies the type that it is going to operator on, preceded by the this keyword.

What is the extension method for a class?

In C#, the extension method concept allows you to add new methods in the existing class or in the structure without modifying the source code of the original type and you do not require any kind of special permission from the original type and there is no need to re-compile the original type.

Can we extend static class in C#?

No, we can't. No, It's not possible to inherit Static class. Static classes are sealed classes so we can't inherit that.


1 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.

like image 103
James Kovacs Avatar answered Sep 21 '22 15:09

James Kovacs