Skip to content

[Proposal] Extension classes with Interfaces #3357

@grwGeo

Description

@grwGeo

I believe that type extensibility (as in extension methods) is a very useful feature that should be viewed as part of a healthy OOP design and not just as compiler deception or syntactic sugar.

Type extensibility can be expanded to the much anticipated extension properties, extension events, indexers etc and even Interface implementation. This last one would be particularly useful should we need to group types owned by others, in interfaces owned by us (or others).

The main advantage of type extension is the ability to intervene high up in an inheritance chain, adding extra functionality to a multitude of types with just one stroke (e.g. imagine adding a custom property to all windows forms controls with just a few lines of code). And with the addition of implementing interfaces this can be a very powerful tool.

I have personally indirectly implemented extension properties and events, so it should be logically consistent to implement these.

A syntax for all these could be similar to partial classes and this could replace current syntax for extension methods as well. So something like this (interface optional of course):
(Here is code)

public extension class OtherOwnersNamespace.OtherOwnersClass : ISomeInterface
{
    private int _myExField = 0;
    public int MyExProperty { get { return _myExField; } }

    public event EventHandler<EventArgs> MyExEvent;  //Could add accessors too.

    internal void MyExMethod() { }
    protected virtual void MyExVirtualMethod() { } //Could be overridden in an extension of an OtherOwnersDerivedClass  
    public static void MyExStaticMethod() { }

    public string this[object someObject] { get { return someString; } }


    void ISomeInterface.SomeInterfaceMethod(){}
}

The 'this' keyword should give us all properties of the original class plus our extension class.
The scope and visibility of the extension class and its members would be the same as if the class was defined normally without the 'extension' keyword.

Current syntax could also remain as an alternative to avoid unnecessary lines of code for cases where (for example) lots of different single extension methods for different types are defined and gathered in one static class.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions