Why does Microsoft create specific Extension Methods? RRS feed

  • Question

  • I wrote my first Extension Method a few days ago.  Extension Methods are a great idea.

    But I don't understand why Microsoft supplies specific Extension Methods.  The documentation for the String Class, for example, has many.  But if you are Microsoft why not supply regular Methods?  I used to avoid even looking at Extension Methods because I hadn't done any research and thus didn't understand what they were.  

    Mostly I am just curious.  But I wonder too if maybe there is something I don't understand about Extension Methods which explains why Microsoft seems to (at least sometimes) prefer Extension Methods to regular Methods.

    Thanks,  Bob

    Sunday, December 1, 2013 6:35 PM


  • Those string extension methods aren't really string specific, they're IEnumerable/IEnumerable<T> extension methods. String implements IEnumerable and IEnumerable<char> so you get all those extensions methods.

    Without extension methods you'd need to implement all those methods in every type which implements IEnumerable and that would lead to a lot of duplication. Or you'd need use the normal static method access syntax and write

    Enumerable.All(str, c => c == '0')

    instead of the more convenient

    str.All(c => c == '0')

    Sunday, December 1, 2013 7:11 PM