Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

I have two classes like this :

public static class AClass {
    public static int AMethod(string ....)
    {
    }
}

and

public static class BClass {
    public static int BMethod(this string ....)
    {
    }
}

I can use these like

AClass.AMethod('...');

or

'...'.BMethod();

Which is proposed ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
192 views
Welcome To Ask or Share your Answers For Others

1 Answer

An extension method is still a static method. You can use it exactly as you'd use a normal static method.

The only difference is that an extension method allows you to use the method in a way that looks like it's part of the type, so you can write:

int result = stringValue.BMethod();

Instead of:

int result = BClass.BMethod(stringValue);

This works purely as a compile "trick" - the compiler sees the first form, and if the BClass is usable (it has a proper using and is in a referenced assembly), then it will turn it into the second method's IL for you. It's purely a convenience.

Which is proposed ?

This really depends. If you control the type, I'd recommend putting the methods on the type itself. This is typically more maintainable.

If you don't control the type, or you're trying to "extend" a common type (such as IEnumerable<T>), then extension methods may be a reasonable approach.

However, if the type is a very common type, I'd typically avoid extension methods, as they become "noise" in intellisense, which in turn can cause extra confusion. For example, I would personally not recommend adding extension methods on System.Object or System.String, etc.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...