csharplang icon indicating copy to clipboard operation
csharplang copied to clipboard

Champion "Extension function members"

Open gafter opened this issue 7 years ago • 76 comments

  • [ ] Proposal added
  • [ ] Discussed in LDM
  • [ ] Decision in LDM
  • [ ] Finalized (done, rejected, inactive)
  • [ ] Spec'ed

See also https://github.com/dotnet/roslyn/issues/11159

gafter avatar Feb 26 '17 20:02 gafter

Almost agree and totally support with a bit of arguments and concerns

  • Name of this feature make it not sure if this will be able to extend field or not, I would disagree to extend fields

  • Extension struct should always pass by reference. Same behaviour as normal implementation of struct. This solve the problem of passing struct by ref for extension method altogether

  • How can we find duplicate operator? When it cause function conflict error it will be hard to find, unlike named member that could go to reference

  • Would this syntax will be able to extend enum ?

  • Is this include extension to implement interface ?

  • We don't need new keyword extension if we could permit static class to extend anything. Reusing keyword and it already intuitive to have static class hold extension method

/// static class cannot extend anything before so it not breaking any previous code
public static class Ext : MyStruct
{
}

Thaina avatar Feb 27 '17 04:02 Thaina

I think I'm late to the party and forgive my ignorance, but what about just supporting partial keyword for non-partial classes ?

Bartmax avatar Jun 07 '17 12:06 Bartmax

@Bartmax partial is for classes in the same assembly. It simply combines several pieces of the same type during compilation. Extensions are for extending arbitrary classes, including those from external compiled assemblies.

orthoxerox avatar Jun 07 '17 12:06 orthoxerox

i know that, but that doesn't mean it can be "reworked" to allow classes from other assemblies hence creating extensions for arbitrary classes.

Bartmax avatar Jun 07 '17 12:06 Bartmax

I'd suggest the following syntax for extension declarations,

internal extension [class] StringExtensions for String { }
internal extension [class] GenericExtensions<T> for T where T : class { }

I believe the name should be optional for convenience (e.g. private nested extension declarations don't really need to be named):

private extension [for] String { }
private extension<T> [for] T where T : class { }

Similarly, instead of base list, we could use implement to plug interface/shape/traits to types,

implement TraitT for String { }
implement<T> FooT for T where T : BarT { }

This has various advantages like segregating impls so that they do not show up on all instances. Explicit implementations could have the same effect in extension declarations, but I think it's good to separate these concerns (auxiliary methods vs trait implementations).

alrz avatar Jul 06 '17 19:07 alrz

Please consider this feature for the nearest releases. It would make life so much easier.

ghost avatar Jul 18 '17 21:07 ghost

I think it would be good to have the ability to write extensions for multiple classes in a single context. For example, if you need to cache reflection objects (especially when you're emitting something), sharing said cache would probably be a good idea, and creating an additional static class for that sole purpose would feel somewhat awkward.

Also, I think many would benefit from extensions existing in a non-global context (consider private static void ExtMethod(this SomeClass x) being inside a non-static class).

hacklex avatar Aug 25 '17 18:08 hacklex

@Bartmax, there is no such thing as partial classes. There are partial class definitions and it's a source code feature not an assembly feature (@orthoxerox).

paulomorgado avatar Aug 26 '17 13:08 paulomorgado

X.0 or 8.0? (See A preview of c# 8 with Mads Torgersen)

gmengano avatar Oct 25 '17 11:10 gmengano

Well, it's 100% in the X.0 Candidate milestone. And you can click it if you don't know what that means.

Joe4evr avatar Oct 25 '17 14:10 Joe4evr

@Joe4evr That milestone has a release date of January 1 2100 - I think most of us would like to see this feature in a version of C# that's released before we're all dead...

IanKemp avatar Nov 08 '17 06:11 IanKemp

@paulomorgado and @orthoxerox, I'm sure @Bartmax is not suggesting using partial class definitions. He's suggesting using a similar syntax to theirs, but for extension members. It's a great idea:

public extension class ClassName
{
    // Extension members of all types go here
    // Don't need to pollute parameter lists with "this ClassName foo"
}

JVimes avatar Nov 29 '17 19:11 JVimes

@JVimes I totally agree with your proposed syntax so not to introduce anymore new keyword like the example with the for keyword. But what about the cases you are implementing extension methods for types that implement a certain interfaces? Event the naming would be misleading. Like we are doing and extension class for IEnumerable<T> and you have to do something like the following:

public extension class IEnumerable<T>
{
    // Extension members of all types go here
    // Don't need to pollute parameter lists with "this ClassName foo"
}

Which breaks the naming conventions for C#. Based on your approach i would go with a syntax like this

public extension class ExtensionName : ClassName 
{
    // Extension members of all types go here
    // Don't need to pollute parameter lists with "this ClassName foo"
}

So it should support the same syntax as class inheritance, generics, etc. The only thing with this approach is that it may be misleading to that user, thinking he should implement the interface or abstract class (as it looks like you are extending/implementing some type.

ivi-hamiti avatar Dec 01 '17 07:12 ivi-hamiti

So, would this proposal cover being able to add events as an extension to an existing class as well?

michael-hawker avatar Dec 17 '17 02:12 michael-hawker

https://github.com/dotnet/roslyn/issues/11159#issue-153598385:

Limitations:

  • Events not permitted (at first)

jnm2 avatar Dec 18 '17 13:12 jnm2

I assume this would support interfaces. This would be really neat, since you could make a mixin like this (with the syntax specified by ivi-hamiti):

interface IMyMixin {}

public extension class MyMixinImpl : IMyMixin {
    // mixin stuff here
}

leo60228 avatar Mar 11 '18 14:03 leo60228

@leo60228 Is there any reason you'd need this over Default Interface Methods #52 to create mixins?

Interfaces will probably be supported just the same, but this proposal is more for the cases where you don't own the type in question.

Joe4evr avatar Mar 13 '18 06:03 Joe4evr

@Joe4evr

  • It keep interface being just interface
  • It can extend across namespace and assembly
  • It more flexible
  • It let we have the same expectation to current extension method. Current extension method support interface and generic constraint. All object implement extended interface can also call all of its extension method. If we could extend all member then this approach is more familiar

Thaina avatar Mar 13 '18 06:03 Thaina

@leo60228

It would support interfaces the same way that extension methods do now.

@Joe4evr @Thaina

The use of extensions here does not replace default method implementations anymore than extension methods currently do. They are external, cannot be virtual/specialized and the feature does not enable safe evolution of existing contracts.

HaloFour avatar Mar 13 '18 10:03 HaloFour

No, didn't see that proposal. Sorry!

On Tue, Mar 13, 2018, 6:52 AM HaloFour [email protected] wrote:

@leo60228 https://github.com/leo60228

It would support interfaces the same way that extension methods do now.

@Joe4evr https://github.com/joe4evr @Thaina https://github.com/thaina

The use of extensions here does not replace default method implementations anymore than extension methods currently do. They are external, cannot be virtual/specialized and the feature does not enable safe evolution of existing contracts.

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/dotnet/csharplang/issues/192#issuecomment-372624840, or mute the thread https://github.com/notifications/unsubscribe-auth/AH996e-Fq-juLIX00Y2Xu-T31qxJfrHtks5td6TsgaJpZM4MMgFz .

leo60228 avatar Mar 13 '18 10:03 leo60228

Type Extensions Syntax Proposition

The following is a syntax and language feature proposition for how extension types would work.

Example

This is an example of what the syntax would look like, assuming all of the types are defined in the same namespace.

Dependency

public class SampleDependedType
{
    public string SampleStringVariableA { get; protected set; } = String.Empty;

    public string SampleStringVariableB { get; set; } = String.Empty;

    public int SampleIntegerVariableA { get; set; } = 0;
}

Hypothetical Extending Class

public extending class SampleExtendingType : SampleDependedType
{
    public string ToString() => $"\{ {SampleStringVariableA}, {SampleStringVariableB}, {SampleIntegerVariableA} \}";

    public void Reset() => (SampleStringVariableA, SampleStringVariableB, SampleIntegerVariableA) = (String.Empty, String.Empty, 0);

    public string SampleStringVariableA { get; set; }
}

Usage of Hypothetical Extending Class

using System;

using static SampleExtendingType;

class Program
{
    static void Main()
    {
        var sampleDependedType = new SampleDependedType { SampleStringVariableA = "Hello" };
        var sampleExtendingType = new SampleExtendingType { SampleStringVariableB = "What is up" };

        Console.WriteLine(sampleDependedType.ToString()); // Result: { Hello, , 0 }
        Console.WriteLine(sampleDependedType.SampleIntegerVariableA == sampleExtendingType.SampleIntegerVariableA); // Result: true

        sampleDependedType.Reset();

        sampleExtendingType.SampleIntegerA = 2;

        Console.WriteLine(sampleDependedType.ToString()); // Result: { , , 0 }
        Console.WriteLine(sampleExtendingType.ToString()); // Result: { , What is up, 2 }

        Console.WriteLine(sampleExtendingType is sampleDependedType); // Result: true
    }
}

Usage Explanation

The keyword extending would be placed on the type declaration for any class that is to be an extension of another; deriving from a class with the extending keyword would cause the new type to extend the derived type. The word extending was chosen to reflect the pattern of using statement words as keywords, such as protected and sealed; extending is being used in reference to the phrase "the extending class", in the same way that the word ageing is being used in reference to the phrase "the ageing oak tree".

The extending type is the one that is the extending class that it is derived from, meaning that the type's definition is defining an extension to the type that was derived from. Using the extending type statically will cause it to be merged in functionality with the class it is extending, but will still be usable as a standalone type, as a normal derived class. The declaration of SampleStringVariableA in the extension class defines an implicit encapsulation of the functionality of SampleStringVariableA from the derived-from type and overrides the access modifier for the setter because the extension type, just as any other derived type, has access to protected setters within the type they are derived from and can thus define a differently-accessible delegate that encapsulates the functionality of the original setter delegate.

Additional Features

Generic Extensions

The system should also allow for the declaration of generic extensions that would programmatically be defined as generic classes with the same non-generic members as the derived-from class. Having this ability would be very useful as it would greatly simplify the process of creating generic and non-generic versions of a class; a publicly-inaccessible base class could be created and derived from in both a generic and a non-generic extension of itself, instantly defining two different types with the same non-generic members and with the same name.

Alternatives

The keyword extending could be switched out with extension but then a double noun issue would be introduced, as the syntactical declaration would already specify the "type" of the syntactical structure being defined, such as class or struct, so specifying extension as well creates ambiguity in what the "type" of the structure is, and what the pseudo-adjective is; is it a class extension or an extension class. It would then be rather more appropriate to replace both words with something like class-extension or extension-class; however, in such a case it would probably be simpler and more intuitive if the keyword class were to be removed altogether. Some may point to abstract class to argue that it would be valid, but the word abstract is an adjective, and so class abstract does not makes sense, which is why it works.

Usefulness

This language feature should be worked on more actively because it can be made into a very useful new tool for easily creating types with common members. Since, according to this pseudo-specification, extensions are in themselves types but with direct syntactical access to, from the perspective of a client, the members of the type that they are derived from, this feature would make it extremely easy to define a bunch of types that all have the same base members such as constructors, indexers, and all else defined and/or declared in the derived-from type. Attributes and/or modifiers would also be copied over. In this case, the keyword to create this syntactical structure should just be extension without any other noun such as class or struct.

TheFanatr avatar Jun 06 '18 07:06 TheFanatr

@TheFanatr protected and sealed are not present-tense words. extended would fit the current pattern of past tense words better.

It'd be also great to see method and operator overload examples in the sample. Also, a call out that while the sample shows the same namespace, that isn't a restriction/limitation of the feature.

michael-hawker avatar Jun 06 '18 18:06 michael-hawker

protected and sealed are not present-tense words

Yeah, I know. I think it's a side effect of the fact that I wrote it at 2 AM.

extended would fit the current pattern of past tense words better

It may fit the pattern better; however, it doesn't make sense. Somewhere in there I explained it, but basically, the extension is doing the extending of the derived type, so consequently, the type that it is extending is the "extended" type, not the other way around.

TheFanatr avatar Jun 06 '18 18:06 TheFanatr

the keyword to create this syntactical structure should just be extension without any other noun such as class or struct.

Exactly.

Gorthog avatar Sep 04 '18 12:09 Gorthog

This would be very helpful writing generic wrapper classes that will override the compare Operator only if the generic type argument supports it.

Do I see it correctly that I would need an separate extension class for every concrete generic type. E.g. My Wraper should support + when the generic type support it. So I will need one class and not only one Method for each type int, double, float, long .....

public class E<T>{ /* ...*/ }

public extension class EExtesnions<T>  : E<T>  where T :IComparable<T>
{
   //...
   public static  E<bool> operator <(E<T> left, E<T> right) => // implementation;

   // this is not allowed vvvv
   public static  E<int> operator +(E<int> left, E<int> right) => // implementation;
   public static  E<double> operator +(E<double> left, E<double> right) => // implementation;
}

public extension class EIntExtension  : E<int> 
{
   //...
   public static  E<int> operator +(E<int> left, E<int> right) => // implementation;
}
public extension class EIntExtension  : E<double> 
{
   //...
   public static  E<double> operator +(E<double> left, E<double> right) => // implementation;
}

LokiMidgard avatar Dec 08 '18 13:12 LokiMidgard

So how about keeping it familiar, but still different enough to not cause confusion - instead of the normal single colon : for inheritance, this could use double colons :: public static class MyExtensions :: ExtendedClass Or has anyone suggested this already?

AnorZaken avatar Apr 10 '19 10:04 AnorZaken

While it isn't commonly used (and wouldn't make sense in that context), it's worth noting that :: is already in use for namespace alias qualifiers.

Personally, I'd rather see the introduction of the extension keyword in place of static for extension types. It puts more emphasis on the fact that the type plays a special role compared to others.

PathogenDavid avatar Apr 10 '19 10:04 PathogenDavid

Rather than having a special type of extensions class, why not modify the existing syntax for extension methods? For example,

public static class DayOfWeekExtensions
{
  // Methods
  public static bool IsWeekend() extends DayOfWeek
  {
     return this == DayOfWeek.Saturday || this == DayOfWeek.Sunday;
  }

  // Properties
  public static bool IsWeekend extends DayOfWeek
  {
     get => this == DayOfWeek.Saturday || this == DayOfWeek.Sunday;
  }
}

The extends keyword defines the context of the this keyword within the body of the extension. This allows for a single extensions class to extend the capabilities of multiple types, as do existing extension classes that currently implement extension methods. Extension methods could also overload methods from the extended type, so long as the method signature is unique. If the extended type is later modified to add an overload that is already defined as an extension, the extension overload would have to be flagged as a compilation error.

You could also extend interfaces, where the this keyword refers to an instance of the interface. For example,

public static class EnumerableExtensions
{
    public static int CountNulls<T>() extends IEnumerable<T> where T : class
    {
        return this.Count(item => item == null);
    }
}

When using generics, as in this example, the generic type arguments would be limited to those employed by the extended type so the compiler would know their context at the point the extension was called.

This strategy could also be applied to other constructs such as indexers.

// Contrived example!
namespace ExtensionsExample
{
    public struct FirstName
    {
        private string _name;

        public FirstName(string name)
        {
            _name = name;
        }
    }

    public struct LastName : IEquatable<LastName>
    {
        private string _name;

        public LastName(string name)
        {
            _name = name;
        }

        public bool Equals(LastName other)
        {
            return other._name == _name;
        }
    }

    public class PersonName
    {
        public FirstName FirstName {get; set;}
        public LastName LastName {get; set;}
    }

    public class PersonNameCollection : CollectionBase
    {
        // Collection stuff.
    }

    public class Person
    {
        public PersonNameCollection Names {get;}
    }

    public static class PersonExtensions
    {
        public static PersonName this[LastName index] extends PersonNameCollection
        {
            get => this.Cast<PersonName>().SingleOrDefault(item => item.LastName.Equals(index));
        }
    }
}

matthew25187 avatar May 08 '19 19:05 matthew25187

How would a class being sealed affect the ability of extensions to add capabilities to it? Would the sealed keyword prohibit the definition of extensions on the class?

matthew25187 avatar May 08 '19 19:05 matthew25187