Coffeehouse Post

Single Post Permalink

View Thread: C#'s biggest mistake
  • User profile image

    I think the way they implemented extension methods is too limited, convoluted and broken. There is a much cleaner and easier way. They should have used the same concept as a "partial" class, and implemented extension methods like this:

    public extension class SomeExistingClass
        // Add whatever instance or static methods you want
        // Add any properties you want
        // You can't add any new fields though...results in compiler error

    The compiler should then impose extension-specific limitations, like the fact that you can't add new fields, but you are now free to add new methods and properties using the exact same syntax that we are already familiar with.

    The advantage here is that there is nothing new that the developer needs to learn other than how to spell "extension". No more weird static methods with the first "this" parameter, full support for properties and static methods, etc.

    EDIT: Oh, and for value types, the "this" parameter should be a ref to the original struct, not a copy of it. Yes, there really are cases where you want to change just one or two values in a struct for performance reasons (see the XNA Matrix class, which consists of 64 bytes and is used in tight loops in 3D games. The existing extension mechanism forces two full copies of a value type if you need to return a modified version of it).

    CLARIFICATION: It seems some people think I'm implying that the class you are extending has to be within the same namespace as the original class. This is not true and this is never what I proposed. The class can be in any other namespace, just like extension methods right now can be in any other namespace. If there are name collisions, you would need to qualify the class you are extending exactly like you would need to qualify it right now with the existing extension mechanism.

    Also, I'm not proposing that the compiler use the exact same restrictions as that of a "partial" class. It is merely a way to demonstrate that there is precedent for similar syntax elsewhere. An extension class will come with its own set of restrictions, and the compiler will enforce those  restrictions. For instance, you would not be able to add new fields etc.