Search code examples
c#extension-methods

What Advantages of Extension Methods have you found?


A "non-believer" of C# was asking me what the purpose to extension methods was. I explained that you could then add new methods to objects that were already defined, especially when you don't own/control the source to the original object.

He brought up "Why not just add a method to your own class?" We've been going round and round (in a good way). My general response is that it is another tool in the toolbelt, and his response is it is a useless waste of a tool... but I thought I'd get a more "enlightened" answer.

What are some scenarios that you've used extension methods that you couldn't have (or shouldn't have) used a method added on to your own class?


Solution

  • I think extension methods help a lot when writing code, if you add extension methods to basic types you'll get them quicky in the intellisense.

    I have a format provider to format a file size. To use it I need to write:

    Console.WriteLine(String.Format(new FileSizeFormatProvider(), "{0:fs}", fileSize));
    

    Creating an extension method I can write:

    Console.WriteLine(fileSize.ToFileSize());
    

    Cleaner and simpler.