Open MadsTorgersen opened 2 days ago
Just to reiterate the Scala 3 approach, which I think does solve for a lot of these problems (although not necessarily all of them). The extensions are member-based, so it's completely unopinionated regarding the container class into which they are declared. However, it also allows grouping the members by target so you don't have to constantly repeat the target for each member. The extension itself can be declared as generic, allowing for generic targets and constraints, and that generic type parameter is flattened into the member signatures as the first generic type parameter. The extension uses primary constructor syntax, so the target declaration is very flexible as to the parameter name and type, and supports annotations like any normal parameter would.
Scala:
// can be declared in any class
object Enumerable {
// single member, non-generic target, generic method
extension (source: Seq[_]) def ofType[T](): Seq[T] = ???
// multiple members, generic target
extension[T] (source: Seq[T]) {
// non generic extension method
def filter(predicate: T => Boolean): Seq[T] = ???
// generic extension method
def map[TR](mapper: T => TR): Seq[TR] = ???
// extension property
def isEmpty: Boolean = ???
// extension operator
def :: (other: Seq[T]): Seq[T] = ???
}
// more complicated generics
extension[T, U] (source: Seq[T]) {
// generic extension operator
def + (other: Seq[U]): Seq[T] = ???
}
// can also include normal members
def Empty[T](): Seq[T] = ???
}
I think the one use case it doesn't cover is when you want a generic target but the generic type parameter is not the first generic type parameter. Actually, nevermind, it does:
// reordered generic type parameters
extension[TR, T] (source: Seq[T]) def map(mapper: T => TR): Seq[TR] = ???
I'm also not sure how that could translate to C# syntax. I guess this is somewhat close to the for
scoping that was suggested earlier.
Anyway, food for thought. I think by borrowing from and combining existing language syntax elements like this it does help to simplify some of the more complicated cases without having to come up with a bunch of new syntax.
Just some personal thoughts... Seeing how complex these considerations get… why do we even need a new kind of syntax for non-role extensions? I’ve wanted extensions properties once or twice, but really it’s not something that would allow entirely new things, or would it? It feels to me maybe not worth it to introduce a new keyword and a new category of type for that.
What I’m really looking forward to is „extension types“ / „roles“ with their own type identities. I would use them soooo much.
Ok, here's something I came up with. As always, there may be dumb fundamental problems or typos. Sorry if I missed something.
The idea is to take hybrid approach. We make all old-style extensions have a corresponding new form which does not require additional syntax to be backwards-compatible. That is, instance extension methods are compatible by default. We split generic parameters in two separate lists. The first list is for parameters which are used primary to bind the extension. The second list is for parameters which are supplied at a call site. Currently, this list is only for methods, because other members can't specify generic paremeters. The actual implementation of the member can take parameters from both lists.
Meet the new
A "for" clause specifies the generic parameters which participate in binding of a member, the underlying type, the receiver mode and its modifiers. At a call site, parameters from the "for" clause are already known for instance members. Parameters from the method declaration are specified by the caller or inferred from the arguments. I probably need to clarify: The motivation for splitting parameters is not only to make uniform syntax possible, but to remove the need to specify already known binding type parameters when you call extension methods with additional type parameters through instance syntax.
Receiver mode is an extension-only concept which determines how you will access the underlying type or the object for which your extension is called.
I will describe 4 possible receiver modes, 2 for instance and 2 for static members. Actually it is sufficient to implement two, the 1st and either the 3rd or the 4th.
<parameter name>
: The extended object is passed as a parameter with the name you provide. The body of the extension sees it as a normal parameter with that name. This is similar to old extension methods.this
: The extended object is passed as a parameter with the name "this". The body of the extension sees it as a receiver. The extension can directly access any of its public members like if they were declared right in the extension type or use "this.Member" notation.
default
: The extended type's members are not directly accessible in the extension body. You can use already declared generics to repeat whatever is in your underlying type declaration to mention the type you are extending. This receiver mode kinda represents an absence of a receiver.self
: This can be used as a good starting point to implement the self-type feature. The extended type's members can be directly accessed in the extension body. The keyword 'self' in the body is a shorthand for whatever is in your underlying type declaration. No actual new possibilities in this context, just sugar.public extension ExtensionA
{
// T goes into "for" because it is used in the underlying type
public void ExtMethod0(int someArg) for <T> List<T> list where T : class?
{
// "list" is a parameter now.
// You can access its members only by referring to them like 'list.Member'
// T is a type you get from binding when you call it like an instance method
}
public void ExtMethod1(int someArg) for <T> List<T> this where T : class?
{
// "this" is the receiver now.
// You can access its members by referring to them like 'this.Member' OR
// just 'Member' like if they were declared right here in the extension
// T is a type you get from binding when you call it like an instance method
}
// Generic parameters not used in the receiver type are specified in the method declaration.
// If generic parameters are present in both the "for" clause and the method declaration, their constraints are specified in a shared "where" clause.
public void ExtMethod2<U>(T someArg1, U someArg) for <T> List<T> this where T : class? where U : struct
{
// "this" is the receiver now.
// You can access its members by referring to them like 'this.Member' OR
// just 'Member' like if they were declared right here in the extension
// T is a type you get from binding when you call it like an instance method
// U is whatever specified at the call site
}
// This is how you include receiver modifiers in a "for" clause.
// It doesn't matter whether it's a named parameter or a this-receiver
public void ExtMethod3(T val) for <T> [SomeAttribute] ref T this where T : struct
{
// "this" is the receiver now. It is passed by-ref and has [SomeAttribute]
// You can access its members by referring to them like 'this.Member' OR
// just 'Member' like if they were declared right here in the extension
// T is a type you get from binding when you call it like an instance method
this = val;
}
// This is how you declare instance extension properties
// You always have to use 'this' as the receiver mode, since named parameter
// doesn't make sense here.
public int ExtProperty for <T> T this where T : class? => 1;
// And indexers (why they still can't named?)
// Although we have parameters here, let's not complicate further and only use 'this'.
public object this[int i] for <T> T this where T : class?
{
get ... set ...
}
// And static methods
// You don't have to specify 'default' receiver mode in this context.
public static T StaticExtMethod() for <T> T where T : class?
{
return ...
}
// self may be useful when you have a long underlying type which you don't want to repeat to access its members
public static T StaticExtMethod2() for <T> TypeA<TypeB<TypeC<T>>> self where T : class?
{
UnderlyingTypeStaticMethod1()
UnderlyingTypeStaticMethod2()
self.UnderlyingTypeStaticMethod3()
return ...
}
// And operators
public static explicit operator int(T obj) for <T> T where T : class?
{
return obj.GetHashCode();
}
// You got the idea
}
List<object> list = new();
int arg = 0;
// 0
list.ExtMethod0(arg);
// 1
list.ExtMethod1(arg);
// 2
list.ExtMethod2<object, int>(new object(), arg);
// Important: See Update 3 for more info.
list.ExtMethod2<.., int>(new object(), arg);
// 3
arg.ExtMethod3(1);
// Instance Property
_ = list.ExtProperty;
// Instance Indexer
_ = list[0];
// Static methods
_ = object.StaticExtMethod();
_ = TypeA<TypeB<TypeC<object>>>.StaticExtMethod2();
// Operator
_ = (int)(new object());
When you call new extension methods like static ones, they appear to you like old ones. The "for" clause parameters are joined with the method parameters.
// 0
ExtensionA.ExtMethod1(list, arg);
// 1
ExtensionA.ExtMethod1(list, arg);
// 2
// Since this method requires additional parameter which cannot be inferred, you have to fill in generics explicitly.
ExtensionA.ExtMethod2<int, int>(list, new object(), arg);
// 3
ExtensionA.ExtMethod3(ref arg, 1);
// The other member kinds don't require compatibility with old extensions.
// They still can be lowered to static members of the extension type.
The "for" clause has moved to the extension type declaration The extension itself is always a static type. Why parameters for the underlying type are still specified in the "for" clause? Because we need to be able to do old-style calls of static methods on the extension type and still have the benefit of not repeating the underlying type in the extension members:
ExtensionA.ExtMethod1(receiver, arg) vs ExtensionA<int>.ExtMethod1(receiver, arg)
But we don't have generic extension types in C#? Well, in type-based approach we will, so this is required to have compatibility and to preserve extension syntax uniformity.
public extension ExtensionA for <T> List<T> where T : class?
{
public void ExtMethod0(int someArg) for list
{
// "list" is a parameter now.
// You can access its members only by referring to them like 'list.Member'
// T is a type you get from binding when you call it like an instance method
}
public void ExtMethod1(int someArg) for this
{
// "this" is the receiver now.
// You can access its members by referring to them like 'this.Member' OR
// just 'Member' like if they were declared right here in the extension
// T is a type you get from binding when you call it like an instance method
}
public void ExtMethod2<U>(T someArg1, U someArg) for this
{
// "this" is the receiver now.
// You can access its members by referring to them like 'this.Member' OR
// just 'Member' like if they were declared right here in the extension
// T is a type you get from binding when you call it like an instance method
// U is whatever specified at the call site
}
}
public extension ExtensionB for <T> T where T : struct
{
public void ExtMethod3(T val) for [SomeAttribute] ref this
{
// "this" is the receiver now. It is passed by-ref and has [SomeAttribute]
// You can access its members by referring to them like 'this.Member' OR
// just 'Member' like if they were declared right here in the extension
// T is a type you get from binding when you call it like an instance method
this = val;
}
}
public extension ExtensionC for <T> T where T : class?
{
public int ExtProperty for this => 1;
public object this[int i] for this
{
get ... set ...
}
// 'default' is one of the static receiver modes and also literally means empty 'for' clause. This is in line with the 'default' generic constraint with similar meaning. It is just there to mark the method as an extension.
// Options for different naming may include '_', 'static', but personally I find 'default' the best.
// Also, since we already have a parent 'for' scope, there is an option to omit the 'for' clause here and make all static members in a 'for' scope extensions by default. I don't like this approach because it makes it impossible to declare non-extension statics if you use a type-based 'for' scope without extracting it to be a child scope like will be shown later.
// And finally an augmentation of the previous way: Another method modifier could be added which means "nonextension".
public static T StaticExtMethod() for default
{
return ...
}
public static explicit operator int(T obj) for default
{
return obj.GetHashCode();
}
}
public extension ExtensionD for <T> TypeA<TypeB<TypeC<T>>> where T : class?
{
public static T StaticExtMethod2() for self
{
UnderlyingTypeStaticMethod1()
UnderlyingTypeStaticMethod2()
self.UnderlyingTypeStaticMethod3()
return ...
}
}
Multiple for
scopes can be specified in an extension type to include extensions for different types. A for
clause on an extension type, as shown in the former example, also denotes a for
scope, it's simply merged with the type declaration. for
scopes can't be nested and they can't include parameter modifiers or receiver mode. These properties belong to for
clauses of each individual member.
public extension ExtensionA
{
for <T> List<T> where T : class?
{
public void ExtMethod0(int someArg) for list
{
// "list" is a parameter now.
// You can access its members only by referring to them like 'list.Member'
// T is a type you get from binding when you call it like an instance method
}
public void ExtMethod1(int someArg) for this
{
// "this" is the receiver now.
// You can access its members by referring to them like 'this.Member' OR
// just 'Member' like if they were declared right here in the extension
// T is a type you get from binding when you call it like an instance method
}
public void ExtMethod2<U>(T someArg1, U someArg) for this
{
// "this" is the receiver now.
// You can access its members by referring to them like 'this.Member' OR
// just 'Member' like if they were declared right here in the extension
// T is a type you get from binding when you call it like an instance method
// U is whatever specified at the call site
}
}
for <T> T where T : struct
{
public void ExtMethod3(T val) for [SomeAttribute] ref this
{
// "this" is the receiver now. It is passed by-ref and has [SomeAttribute]
// You can access its members by referring to them like 'list.Member' OR
// just 'Member' like if they were declared right here in the extension
// T is a type you get from binding when you call it like an instance method
this = val;
}
}
for <T> T where T : class?
{
public int ExtProperty for this => 1;
public object this[int i] for this
{
get ... set ...
}
public static T StaticExtMethod() for default
{
return ...
}
public static explicit operator int(T obj) for default
{
return obj.GetHashCode();
}
}
for <T> TypeA<TypeB<TypeC<T>>> where T : class?
{
public static T StaticExtMethod2() for self
{
UnderlyingTypeStaticMethod1()
UnderlyingTypeStaticMethod2()
self.UnderlyingTypeStaticMethod3()
return ...
}
}
}
There is a problem when it comes to the instance syntax for methods. With old-style extensions the only way you can specify type arguments in instance calls is to specify all of them or none. But in the context of this "proposal" you can only specify those which are directly declared on the method. And here that problem arises. We have to support the old syntax where you specify all arguments too. But if we were to support both ways, adding a new method with the same signature besides a different number of generic parameters would become a breaking change.
Suppose we have a call obj.A<object>()
And extension:
public void A() for <T> T
If we add a new extension
public void A<U>() for <T> T
obj.A<object>()
should mean the same A with no method-decl params. So, parameters from the for clause could have priority over method-decl ones.
But if we had that extension initially
public void A<U>() for <T> T
obj.A<object>()
would mean the A with one method-decl param.
So adding
public void A() for <T> T
becomes a breaking change, as obj.A<object>()
now calls the A with no method-decl params.
This is a nasty compatibility problem which I overlooked and unfortunately I can't see a really clean way to counter it.
One way we can make it is to remove the ability to do instance calls without filling for-clause generic params and require something explicit like obj.A<.., object>()
if we want to do an instance extension call with generics filled partially. ".." would mean "automatically fill in all for-clause generic parameters"
This way we kind of preserve the benefit of split generics.
Initially I supposed that only this-receiver form will be used with new extensions. However to
I decided to change this part of design and introduce a concept of receiver modes. The main part of the post is updated to incorporate this change.
public partial extension Enumerable
{
for <TSource> IEnumerable<TSource>
{
public IEnumerable<IGrouping<TKey, TElement>> GroupBy<TKey, TElement>(Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector) for source => ...;
}
}
lowers to
public static partial class Enumerable
{
public static IEnumerable<IGrouping<TKey, TElement>> GroupBy<TSource, TKey, TElement>(IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector) => ...;
}
public partial extension MemoryExtensions
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Span<T> AsSpan(int start, int length) for <T> T[]? array
{
return new Span<T>(array, start, length);
}
}
lowers to
public static partial class MemoryExtensions
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Span<T> AsSpan<T>(T[]? array, int start, int length)
{
return new Span<T>(array, start, length);
}
}
If it is not clear from the post, one of the goals of this design is to support both the type and member approaches simultaneously allowing you to choose which one is a better fit for your use case. They are not presented as separate design options here.
We can introduce a self
type for the type being extended and borrow the method type parameter syntax for self
type. Here the self
type will be substituted by the actual type being extended.
extension_member: ... identifier self_type? '(' parameter_list ')'
generic_type_param_with_self: '<' self_type? generic_type_param '>'
self_type: attribute_list? ('ref' | 'ref readonly' | 'in')? 'self' '?'? '*'?
generic_type_param: ',' attribute_list? identifier generic_type_param?
attribute_list: '[' attribute ']' attribute_list?
attribute: attr_type... ','?
public extension TupleExtensions for (int x, int y)
{
public void Swap<ref self>() => (x, y) = (y, x); // `this` is by ref and can be mutated
public int Sum<ref readonly self>() => x + y; // `this` is ref readonly and cannot me mutated
public int Sum<self*>() => this->x + this->y; // `this` is a pointer
}
public extension StringExtension for string
{
public string Reverse() => ...; // instance member
public string Reverse2<self>() => ...; // instance member, but with an explicit self, which is equivalent to `Reverse`
public static string Create() => ...; // static member
public bool IsNullOrEmpty<[NotNullWhen(false)] self?>() => this is null or []; // this is string?
}
public extension GenericExtension<T> for Foo<T> where T : struct
{
public U Bar<[Foo] ref self, U>() where U : class => ...; // some generic example
}
Just like extension methods we already have today where we require users to put a this
parameter as the first parameter, in the new extensions, we can require users to put a self
type parameter as the first type parameter (it's not a real type parameter though).
I think this should be able to handle all the cases we want to cover.
Alternatively, we can still introduce a self
type and require users to put it on the first parameter if the extension member is an instance member:
public extension TupleExtensions for ref (int x, int y)
{
public void Swap() => (x, y) = (y, x); // `this` is by ref and can be mutated
public readonly int Sum => x + y; // `this` is ref readonly and cannot me mutated
}
public extension NullableStringExtension for string?
{
[this:NotNullWhen(false)] public bool IsNullOrEmpty => this is null or [];
}
public extension StringExtension for string
{
public string Reverse() => ...;
}
becomes
public extension TupleExtensions for (int x, int y)
{
public void Swap(ref self) => (x, y) = (y, x); // `this` is by ref and can be mutated
public int Sum(ref readonly self) => x + y; // `this` is ref readonly and cannot me mutated
}
public extension StringExtension for string
{
public bool IsNullOrEmpty([NotNullWhen(false)] self?) => this is null or [];
public string Reverse(self) => ...;
}
and an extension member without self
as the first parameter becomes static automatically.
public extension StringExtension for string
{
public string Reverse(self) => ...; // instance member
public string Create() => ...; // static member
}
However, in this alternative, we don't use static
to specify whether a member is static or not. But extensions are new concept in C#, I do think it can apply some different rules than existing types.
There's no dedicated thread on disambiguation mechanism but I wanted to bring it up as I just hit this with ToListAsync extension in efcore and mongo driver.
I believe the cast operator was considered for properties ((E)e).Prop
which supposedly works for methods as well but it has the same problem with await
: it's a prefix operator.
I think a postfix operator is ideal as the point of an extension is to be able to dot off an expression and chain members.
e.(MongoQueryable).ToListAsync()
Using golang syntax there to demonstrate but anything similar is much easier to read and write, perhaps opens up the discussion on postfix await as well.
@alrz
I believe it had been settled that extensions aren't types that you can declare or cast a value to, so that would mean disambiguation would happen like they do with extension methods today, as a static method invocation, e.g. E.ToListAsync(e)
I believe it had been settled that extensions aren't types that you can declare or cast a value to
This wouldn't be a proper "cast" in that sense though, I'm referring to this proposal: https://github.com/dotnet/csharplang/blob/main/proposals/extensions_v2.md#disambiguation
If that option is no longer on the table, how extension properties are going to be disambiguated? E.get_Prop(e)
?
@alrz
If that option is no longer on the table, how extension properties are going to be disambiguated?
E.get_Prop(e)
?
I think so, although I guess everything is on the table at the moment. There have been so many meetings/discussions on extensions recently that it all kinda blends, but it sounds like extensions won't be "types" in their own right, and if you can't have a value of the extension type does it make sense to be able to have a pseudocast to an extension type?
If extensions lower to a static class, the no-cast role is already in place so that wouldn't be something new and is consistent with the actual emitted code.
if you can't have a value of the extension type does it make sense to be able to have a pseudocast to an extension type?
The proposal does mention this confusion as a drawback so I assume the syntax is not final. I am NOT proposing to add a new cast-operator, but I do think a postfix form works best when talking about extensions.
The proposal does mention this confusion as a drawback so I assume the syntax is not final. I am NOT proposing to add a new cast-operator, but I do think a postfix form works best when talking about extensions.
We shall see what happens. I assume that extension disambiguation will probably remain a relatively rare thing, so I doubt it would move the needle a whole lot on the existing proposals for postfix cast or await anymore than any of the existing use cases.
A classic extension method can specify the underlying type as a nullable reference type. It is fairly rare (< 2%) but allows for useful scenarios, since, unlike instance members, extension members can actually have useful behavior when invoked on null.
Something being useful, especially when it's not widely used already, shouldn't be enough of a justification to take it into account when designing a new feature - extensions. Given that it's merely a syntactic difference which can account for at most a few extra keystrokes (like the previously discussed ((string?)null).LetterCount
vs ((string?)null)?.LetterCount ?? 0
, or s.IsNullOrEmpty()
vs string.IsNullOrEmpty(s)
, the size of the monkey wrench being thrown into the mix just doesn't outweigh the benefits, IMO.
Regarding being "useful", there have been requests (at least once or twice that I've seen) to allow things like:
string? s = null;
// ...
if (s) // instead of if(s != null)
{
// ...
}
The usefulness of the above "implicit not-null-truthiness" is similar to the usefulness of accessing members on a null value, yet C# (rightfully!) rejects this idea. Similarly, I think C# should reject the idea of instance members on null values.
Regarding ref
:
public extension TupleExtensions for ref (int x, int y)
{
public void Swap() => (x, y) = (y, x); // `this` is by ref and can be mutated
public readonly int Sum => x + y; // `this` is ref readonly and cannot me mutated
}
I like this a lot, but I do want to point out a minor complication, imagine the below:
public extension TupleExtensions for ref (int x, int y)
{
public void SwapAndAdd() => (x, y) = (y + this.Sum, x + this.Sum); // `this` is by ref and can be mutated
}
public extension TupleExtensions for (int x, int y)
{
public int Sum => x + y;
}
In the SwapAndAdd
, it would have to create a local copy in order to call the Sum
(which is an extension on the value type in this scenario), which introduces a performance hit. The solution can be to stipulate that the Sum
is emitted twice, once in native form (by value) and once more in by ref form, and then SwapAndAdd
can then call the by ref form behind the scenes, avoiding a copy.
We couldn't find a reasonable way to represent interface-implementing extensions in the runtime.
If this is caused by the requirement that the received interface reference can be reference equal (and "identity equal" in other ways, like GetType()
) to the underlying instance, then I would re-iterate my previously stated opinion on the matter: giving up on such a useful feature for the arguably very few edge cases where reference equality is expected to be used in this way, is not justified. I'm pretty sure most people would prefer to have extension interfaces without identity equality, than no extension interfaces at all. And the former can be trivially achieved with what's available in the runtime today.
TLDR, I think we should go with the syntactically type based approach, and choose the correct emit strategy which satisfies the requirements in the best possible way technically, leaving it to be an implementation detail. Backwards compatibility can be easily achieved by leaving existing extension methods as redirect stubs, and thought-out management of overload resolution.
yet C# (rightfully!) rejects this idea
Humorously, extensions would enable this. As you'd now be any to add extension conversions to bool, as well as operator true/false
.
PS. Having said "implementation detail", I realized that for other languages to be able to use these new C#-compiled extensions, we may want to spec the emitting strategy after all.
yet C# (rightfully!) rejects this idea
Humorously, extensions would enable this. As you'd now be any to add extension conversions to bool, as well as
operator true/false
.
I thought about that a few days ago myself :rofl: This is less than ideal, but ultimately, it would be a particular team engaging in such shenanigans, and C# cannot possibly stop all the foot-guns out there.
It's not a foot gun. These conversations exist exactly to allow these scenarios.
I know from previous conversations with you that there are things that are allowed that you don't like. But these aren't mistakes, or things that accidentally crept in. They were explicit design decisions to enable these types of scenarios.
We had the choice to block them, and we thought about it and explicitly said that we wanted people to be able to do this. Since then people have done this, and everything has been completely fine. The only argument I've seen so far is that someone doesn't like it.
But that's an argument for removing practically everything in the language.
I guess we have a philosophical difference on this subject. I think one of the original objectives of C# to always try creating pits of success and avoid creating pits of failure, is extremely valuable. If a particular limitation prevents a specific use case, I'm all for looking into it - everybody can speak up here and request something or complain about limitations (and people do). And in some cases, lifting existing limitations makes sense. My argument for not allowing accessing instance extension members on nulls is not merely a personal preference; not a matter of "taste". I think the inconsistency with native instance members in this regard is an objective argument against such syntax. I know, "consistency" is not the end-all-be-all, but in this case, we are explicitly saying, "these members are designed to supplement existing members". Yet they follow a completely different methodology WRT nullability? Besides, it's easier to ship the feature without calling instance members on null, and look at community feedback later. If there are hoards of people asking for this, you guys can say - thanks for your input, but we have many more voices who want this, so we'll add it, and at the end of the day, it doesn't really "harm" me personally that much. In fact, it's a win-win: we ship the feature quicker now; we can potentially end up with a design which is more "pit of success"; and if people really want it, it can be debated together with other requests, per the usual design conveyor.
@TahirAhmadov
Besides, it's easier to ship the feature without calling instance members on null
It would require more design work, and more runtime overhead, for the compiler to try to prevent this.
People have already decided with extension methods that they want this. I want this, and I do use it. We're not relitigating the concept of extensions, we're extending it.
I think one of the original objectives of C# to always try creating pits of success and avoid creating pits of failure, is extremely valuable.
I think that is a major design goal. The difference here is that I look at the outcomes of our intentional design decisions and see that they were successful. So why start blocking things that were not a mistake?
Note: the same concerns you have here were the ones levied by many in the community about extension methods entirely. The idea that you appear to have instance methods exposed that you did not write was so completely and obviously wrong to some people, it was literally predicted that the feature would cement the death of the language. :-)
I look at the flexibility we offered, and I see how the community has used it well. And I don't see a good reason to take away.
I think the inconsistency with native instance members in this regard is an objective argument against such syntax.
This was strongly considered and discussed at the time. It was not accidental. And there were a few people that thought the same, including wanting null checks automatically emitted.
In the end, the benefits of letting methods execute on null far outweighed those concerns. Since then, we've had 20 years to reflect on this and to see how the community would do things. Would they reject such methods. Would they make analyzers that require a null+throw check.
In the end, that didn't happen. The community embraced this capability, and they showed that flexibility in extensions could be used to great effect.
You may find that a pity. But that's really not selling me on breaking things that have been part and parcel of this design space for decades now :-)
@TahirAhmadov
Besides, it's easier to ship the feature without calling instance members on null
It would require more design work, and more runtime overhead, for the compiler to try to prevent this.
People have already decided with extension methods that they want this. I want this, and I do use it. We're not relitigating the concept of extensions, we're extending it.
thanks for your input, but we have many more voices who want this, so we'll add it, and at the end of the day
Note, doing this in a non-breaking way would be challenging. People would absolutely start depending on that, and then we would not be able to change it. So we'd need new syntax for that capability.
I think the inconsistency with native instance members in this regard is an objective argument against such syntax.
This was strongly considered and discussed at the time. It was not accidental. And there were a few people that thought the same, including wanting null checks automatically emitted.
In the end, the benefits of letting methods execute on null far outweighed those concerns. Since then, we've had 20 years to reflect on this and to see how the community would do things. Would they reject such methods. Would they make analyzers that require a null+throw check.
In the end, that didn't happen. The community embraced this capability, and they showed that flexibility in extensions could be used to great effect.
You may find that a pity. But that's really not selling me on breaking things that have been part and parcel of this design space for decades now :-)
The exact same thing can be written 20 years after string? s = null; if(s) { ... }
is allowed natively in the language: lone voices against it, overwhelming embrace by the community, and expansion of the language in a similar direction (who says we cannot implicitly convert a string to an int, if the string represents a valid int? it's useful, people love it, etc.! ) :rofl:
People have already decided with extension methods that they want this. I want this, and I do use it. We're not relitigating the concept of extensions, we're extending it.
Extensions are a new feature. It's not merely an "extension" (haha) of extension methods.
Anyway, I wrote everything there is to write about this.
@TahirAhmadov
Extensions are a new feature. It's not merely an "extension" (haha) of extension methods.
I disagree, but even if that were the case I don't see why the team would make a different decision here. I understand that you disagree with the decision, but they (and I) consider it to be a success, thus it would make sense to retain that same capability here.
Is there going to be a mechanism by which to indicate to nullability analysis that an extension method does not accept null? Or are all extensions providing functionality that doesn't make sense without an instance going to require null guard boilerplate to play well with nullability analysis?
@DanFTRX
Is there going to be a mechanism by which to indicate to nullability analysis that an extension method does not accept null? Or are all extensions providing functionality that doesn't make sense without an instance going to require null guard boilerplate to play well with nullability analysis?
That already exists with extension methods today. If the extension target is a non-nullable reference type, you'll get a warning if you try to invoke that extension.
I would be grateful if someone experienced checked my "proposal" here for potential "holes". Just to know if there are already no-go's and I should drop it. Or maybe it is not clear enough and looks insane.
So if I'm reading this right, neither approach will actually let us implement interfaces with extensions? To me that was the primary benefit of dedicated extensions, and without that, I'm not sure this whole thing is worth it.
If people are really clamoring for extension properties/operators then a member-only approach seems preferable, ideally as close to the existing extension method syntax as possible.
If people are really clamoring for extension properties/operators
This is the request. And it's not a random smattering either. It's teams like the runtime, which very much wants to design apis that take advantage of that :-)
Dart lang has a good design for extension https://dart.dev/language/extension-methods
and extension type https://dart.dev/language/extension-types.
IMO, Extension type look good and elegant
@0x0737
I would be grateful if someone experienced checked my "proposal" here for potential "holes".
The exercise I've been going through is how existing extension methods would map to any new syntax, and how that lowers to something that doesn't result in either binary or source breaking changes. Particularly cases like System.Linq.Enumerable
and System.MemoryExtensions
where some of the challenges have been identified.
@HaloFour
The exercise I've been going through is how existing extension methods would map to any new syntax
Thanks for taking a look! Are there any particular methods you would like to see in the new syntax? I'll update the post later with examples.
public extensions ArrayMemoryExtensions<T> for T[]? { public Span<T> (array).AsSpan { get; } } public extensions ArraySegmentMemoryExtensions<T> for ArraySegment<T>? { public Span<T> (segment).AsSpan { get; } }
Why do they need to be separate extension types? Can't they just be made partial?
public partial extensions MemoryExtensions<T> for T[]?
{
public Span<T> (array).AsSpan { get; }
}
public partial extensions MemoryExtensions<T> for ArraySegment<T>?
{
public Span<T> (segment).AsSpan { get; }
}
@HaloFour Post updated. Added some examples. I'm not sure whether they are what you expect. Please elaborate on what cases you want to see dissected. Some syntax got refactored primarily to not require parameter name attributes.
@0x0737
Added some examples. I'm not sure whether they are what you expect. Please elaborate on what cases you want to see dissected. Some syntax got refactored primarily to not require parameter name attributes.
These are just the use cases I try to work out. A lot of the concerns mentioned arise from attempting to "migrate" existing extension methods and supporting all of their different shapes without causing binary or source breaking changes. That includes stuff like retaining compatible signatures with generics, supporting multiple targets within a single extension class, supporting ref
targets for value types and even explicitly naming the this
parameter.
That includes stuff like retaining compatible signatures with generics, supporting multiple targets within a single extension class, supporting ref targets for value types and even explicitly naming the this parameter.
I think those that are merely for compatibility don't necessarily need to affect the overal syntax, so that the base usage remain simple. That would rule out all the member-based options.
@alrz
I think those that are merely for compatibility don't necessarily need to affect the overal syntax, so that the base usage remain simple. That would rule out all the member-based options.
Maybe, but if that compatibility can be accomplished without having to invent a third version of the syntax I think that would be ideal. I think many people will naturally want to migrate their existing extension methods, and if they don't have a good way to do so that doesn't break things and also doesn't lead half-way to another dead end, I think that conversation would be dead on arrival and most libraries would simply never migrate. Also, the design here greatly affects the recommendations for declaring extensions in the future. If they're type based, are we ok with splitting up similar extensions across multiple underlying types, or are there other ways to address that? We know what the guidelines are regarding extension methods, doing something different will require new guidelines.
I think those that are merely for compatibility don't necessarily need to affect the overal syntax
Things like ref-ness are about more than compat. They're a requirement to get acceptable perf for partner teams. Neither approach of always being by ref or by value are good enough.
Things like ref-ness are about more than compat.
I didn't suggest that they are not, but I think that's still not a reason to fallback to member-based approach. If the extension is declared as for ref
, all members would have a ref receiver.
The complexity comes from the fact that you want to define varying ref-ness within the same container and as mentioned elsewhere I do think partial extensions could cover that scenario, yet, the base usage remains a plain extension type with instance members, as originally proposed.
If you allow ref-types and partial groups, that is the member based approach to me :-D
By "for ref" I mean whatever syntax is used to specify the target on the extension definition, not members.
@CyrusNajmabadi Since this thread is for general extension design debates, should I move my large post to a new discussion thread?
I agree with @HaloFour that within a static class some type of scoped section specifying each target type seems to solve a lot of the problems illustrated in the notes.
That said, the notes seem to suggest "extension interfaces" may actually be impossible. If that's the case, and it's never going to happen, I don't think this feature is worth doing at all. Calling extension methods with slightly different syntax, which is all properties/events/operators are, is not worth the huge design effort and language complexity.
Even if we absolutely must have extensions on nullable objects, the proposed this
attribute annotation:
public extension StringExtension for string
{
[this:AllowNull][this:NotNullWhen(false)] public bool IsNullOrEmpty => this is null or [];
public string Reverse() => ...;
}
Seems to be a decent solution.
With the ref
being solved by specifying it in the for
clause of the extension type, at this point it's not clear to me what other scenarios necessitate by-member approach.
I still think binary compatibility should be achieved with redirects and not by trying to match the emit strategy to mimic existing static classes with extension methods; the latter seems to be a much more risky path, than former, which allows the users to ensure that they have the exact same signatures as before, while giving them complete control over their transition timetable.
@TahirAhmadov
Or, you could continue to do what you could always do with extension methods, and if you don't want to accept a null
target, include a null
check. Having the compiler emit one by default makes the common case slow for everybody unnecessarily.
the latter seems to be a much more risky path
It's definitely not. It's much easier and safer if it's just reusing all the existing code paths we already have.
@MgSam But is it really just syntax? there are things that aren't supported by extensions methods today like static types not to mention expressiveness and composition but whatever they might do I really think they should consider interfaces and allow extensions to evolve and be and feel like first-class citizen in the language as opposed to other features such as expression trees... Personally I don't think that just because it's a difficult problem they should stop trying , extension methods have been a success so I can't see why this wouldn't and I really think that if done right it can open the door for many scenarios and contribute greatly to the .NET ecosystem.
A language with over 20 years of history will require significant design effort to incorporate any major new features, especially when taking compatibility and migration into account.
The design space for extensions
Let's put the current proposals for extensions in a broader context, and compare their pros and cons.
Background: How we got here
The competing approaches and philosophies around how to express the declaration of extension members trace their roots all the way back to when extension methods were first designed.
C# 3: The start of extension methods
C# 3 shipped with the extension methods we know today. But their design was not a given: An alternative proposal was on the table which organized extension methods in type-like declarations, each for one specific extended (underlying) type. In this model, extension method declarations would look like instance method declarations, and future addition of other member kinds - even interfaces - would be syntactically straightforward. I cannot find direct references to this first type-based proposal, but here is a slightly later version from 2009 that was inspired by it:
Ultimately the current design was chosen for several reasons. Importantly it was much simpler: a syntactic hack on top of static methods. C# 3 was already brimming with heavy-duty features - lambdas, expression trees, query expressions, advanced type inference, etc. - so the appetite to go big on extension methods was limited. Moreover, the static method approach came with its own disambiguation mechanism - just call as a static method! - and allowed convenient grouping of extension methods within one static class declaration. The extension methods of
System.Linq.Enumerable
would have needed to be spread across about 15 extension type declarations if they had been split by underlying type.But perhaps most significantly, we didn't know extension methods were going to be such a hit. There was a lot of skepticism in the community, especially around the risks of someone else being able to add members to your type. The full usefulness of the paradigm was not obvious even to us at the time; mostly we needed them for the query scenario to come together elegantly. So betting on them as a full-fledged new feature direction felt like a risky choice. Better to keep them a cheap hack to start with.
C# 4: Foundered attempts at extension members
Of course extension methods were a huge success in their own right, and the community was immediately asking for more; especially extension properties and extension interfaces. The LDM went to work on trying to generalize to all member kinds, but felt captive to the choices made in C# 3. We felt extension members would have to be a continuation, not just philosophically but syntactically, of the extension methods we'd shipped. For instance, extension properties would have to either use property syntax and take an extra
this
parameter somehow, or we'd need to operate at the lowered level ofset
andget
methods representing the accessors of properties. Here is an example from 2008:These explorations led to proposals of unbearable complexity, and after much design and implementation effort they were abandoned. At the time we were not ready to consider rebooting extensions with an alternative syntax, one that would leave the popular classic extension methods behind as a sort of legacy syntax.
The return of type-based extensions
The Haskell programming language has type classes, which describe the relationships within groups of types and functions, and which, crucially, can be applied after the fact, without those types and functions participating. A proposal from Microsoft Research in Cambridge for adding type classes to C# triggered a string of proposals that eventually led back to extension interfaces: If extension members could somehow help a type implement an interface without the involvement of that type, this would facilitate similar adaptation capabilities to what type classes provide in Haskell, and would greatly aid software composition.
Extension interfaces fit well with the old alternative idea that extensions were a form of type declaration, so much so that we ended up with a grand plan where extensions were types, and where such types would even be a first class feature of their own - separate from the automatic extension of underlying types - in the form of roles.
This approach ran into several consecutive setbacks: We couldn't find a reasonable way to represent interface-implementing extensions in the runtime. Then the implementation of the "typeness" of extensions proved prohibitively expensive. In the end, the proposal had to be pared back to something much like the old alternative design from above: extensions as type declarations, but with no "typeness" and no roles. Here's a recent 2024 example:
We will refer to the resulting flavor of design as "type-based extensions", because the underlying type of the extension is specified on the extension type itself, and the members are just "normal" instance and static member declarations, including providing access to the underlying value with the
this
keyword rather than a parameter.The return of member-based extensions
Now that the bigger story of extensions as types with interfaces has been put on hold with its future prospects in question, it is worth asking: Are we still on the right syntactic and philosophical path? Perhaps we should instead do something that is more of a continuation of classic extension methods, and is capable of bringing those along in a compatible way.
This has led to several proposals that we will collectively refer to as "member-based extensions". Unlike most of the abandoned C# 4 designs of yore, these designs do break with classic extension methods syntactically. Like the type-based approach they embrace an extension member declaration syntax that is based on the corresponding instance member declaration syntax from classes and structs. However, unlike type-based extensions, the underlying type is expressed at the member level, using new syntax that retains more characteristics of a parameter.
Here are a few examples from this recent proposal:
The motivation is not just a closer philosophical relationship with classic extension methods: It is an explicit goal that existing classic extension methods can be ported to the new syntax in such a way that they remain source and binary compatible. This includes allowing them to be called as static methods, when their declarations follow a certain pattern.
We've had much less time to explore this approach. There are many possible syntactic directions, and we are just now beginning to tease out which properties are inherent to the approach, and which are the result of specific syntax choices. Which leads us to the following section, trying to compare and contrast the two approaches.
Comparing type-based and member-based proposals
Both approaches agree on a number of important points, even as the underlying philosophy differs in what currently feels like fundamental ways:
extension
orextensions
) to hold extension member declarations. Neither approach keeps extension members in static classes.And of course both approaches share the same overarching goal: to be able to facilitate extension members of nearly every member kind, not just instance methods. Either now or in the future this may include instance and static methods, properties, indexers, events, operators, constructors, user-defined conversions, and even static fields. The only exception is members that add instance state, such as instance fields, auto-properties and field-like events.
The similarities make it tempting to search for a middle ground, but we haven't found satisfactory compromise proposals (though not for lack of trying). Most likely this is because the differences are pretty fundamental. So let's look at what divides the two approaches.
Relationship to classic extension methods
The core differentiating factor between the two approaches is how they relate to classic extension methods.
In the member-based approach, it is a key goal that existing classic extension methods be able to migrate to the new syntax with 100% source and binary compatibility. This includes being able to continue to call them directly as static methods, even though they are no longer directly declared as such. A lot of design choices for the feature flow from there: The underlying type is specified in the style of a parameter, including parameter name and potential ref-kinds. The body refers to the underlying value through the parameter name.
Only instance extension methods declared within a non-generic
extensions
declaration are compatible and can be called as static methods, and the signature of that static method is no longer self-evident in the declaration syntax.The type-based approach also aims for comparable expressiveness to classic extension methods, but without the goal of bringing them forward compatibly. Instead it has a different key objective, which is to declare extension members with the same syntax as the instance and static members they "pretend" to be, leaving the specification of the underlying type to the enclosing type declaration. This "thicker" abstraction cannot compatibly represent existing classic extension methods. People who want their existing extension methods to stay fully compatible can instead leave them as they are, and they will play well with new extension members.
While the type-based approach looks like any other class or struct declaration, this may be deceptive and lead to surprises when things don't work the same way.
The member-based approach is arguably more contiguous with classic extension methods, whereas the type-based approach is arguably simpler. Which has more weight?
Handling type parameters
An area where the member-based approach runs into complexity is when the underlying type is an open generic type. We know from existing extension methods that this is quite frequent, not least in the core .NET libraries where about 30% of extension methods have an open generic underlying type. This includes nearly all extension methods in
System.Linq.Enumerable
andSystem.MemoryExtensions
.Classic extension methods facilitate this through one or (occasionally) more type parameters on the static method that occur in the
this
parameter's type:The same approach can be used to - compatibly - declare such a method with the member-based approach:
We should assume that open generic underlying types would be similarly frequent for other extension member kinds, such as properties and operators. However, those kinds of member declarations don't come with the ability to declare type parameters. If we were to declare
AsSpan
as a property, where to declare theT
?This is a non-issue for the type-based approach, which always has type parameters and underlying type on the enclosing
extension
type declaration.For the member-based approach there seem to be two options:
Both lead to significant complication:
Type parameters on non-method extension members
Syntactically we can probably find a place to put type parameters on each kind of member. But other questions abound: Should these be allowed on non-extension members too? If so, how does that work, and if not, why not? How are type arguments explicitly passed to each member kind when they can't be inferred - or are they always inferred?
This seems like a big language extension to bite off, especially since type parameters on other members isn't really a goal, and current proposals don't go there.
Allow type parameters and underlying type to be specified on the enclosing type declaration
If the enclosing
extensions
type declaration can specify type parameters and underlying type, that would give members such as properties a place to put an open generic underlying type without themselves having type parameters:This is indeed how current member-based proposals address the situation. However, this raises its own set of complexities:
extensions
declaration starts carrying crucial information for at least some scenarios.extensions
declaration specifies an underlying type, it can no longer be shared between extension members with different underlying types. The grouping of extension members with different underlying types that is one of the benefits of the member-based approach doesn't actually work when non-method extension members with open generic underlying types are involved: You need separateextensions
declarations with separate type-level underlying types just as in the type-based approach!In summary, classic extension methods rely critically on static methods being able to specify both parameters and type parameters. A member-based approach must either extend that capability fully to other member kinds, or it must partially embrace a type-based approach.
Tweaking parameter semantics
An area where the type-based approach runs into complexity is when the default behavior for how the underlying value is referenced does not suffice, and the syntax suffers from not having the expressiveness of "parameter syntax" for the underlying value.
This is a non-issue for the member-based approach, which allows all this detail to be specified on each member.
There are several kinds of information one might want to specify on the underlying value:
By-ref or by_value for underlying value types
In classic extension methods, the fact that the
this
parameter is a parameter can be used to specify details about it that real instance methods don't get to specify about howthis
works in their body. By default,this
parameters, like all parameters, are passed by value. However, if the underlying type is a value type they can also be specified asref
,ref readonly
andin
. The benefit is to avoid copying of large structs and - in the case ofref
- to enable mutation of the receiver itself rather than a copy.The use of this varies wildly, but is sometimes very high. Measuring across a few different libraries, the percentage of existing extension methods on value types that take the underlying value by reference ranges from 2% to 78%!
The type-based approach abstracts away the parameter passing semantics of the underlying value - extension instance members just reference it using
this
, in analogy with instance members in classes and structs. But classes and structs have different "parameter passing" semantics forthis
! In classesthis
is by-value, and in structsthis
is byref
- orref readonly
when the member or struct is declaredreadonly
.There are two reasonable designs for what the default should be for extension members:
this
by value, and when it is a value type passthis
byref
(or perhapsref readonly
when the member isreadonly
). In the rare case (<2%) that the underlying type is an unconstrained type parameter, decide at runtime.this
by value.Either way, the default will be wrong for some significant number of extension members on value types! Passing by value prevents mutation. Passing by reference is unnecessarily expensive for small value types.
In order to get to reasonable expressiveness on this, the type-based approach would need to break the abstraction and get a little more "parameter-like" with the underlying type. For instance, the
for
clause might optionally specifyref
orin
:Attributes
This-parameters can have attributes. It is quite rare (< 1%), and the vast majority are nullability-related. Of course, extension members can have attributes, but they would need a way to specify that an attribute goes on the implicit
this
parameter!One way is to introduce an additional attribute target, say
this
, which can be put on instance extension members:Nullable reference types
A classic extension method can specify the underlying type as a nullable reference type. It is fairly rare (< 2%) but allows for useful scenarios, since, unlike instance members, extension members can actually have useful behavior when invoked on null. Anotating the receiver as nullable allows the extension method to be called without warning on a value that may be null, in exchange for its body dealing with the possibility that the parameter may be null.
A type-based approach could certainly allow the
for
clause to specify a nullable reference type as the underlying type. However, not all extension members on that type might want it to be nullable, and forcing them to be split across twoextension
declarations seems to break with the ideal that nullability shouldn't have semantic impact:It would be better if nullability could be specified at the member level. But how? Adding new syntax to members seems to be exactly what the type-based approach is trying to avoid! The best bet may be using an attribute with the
this
target as introduced above:This would allow extension members on nullable and nonnullable versions of the same underlying reference type to be grouped together.
Grouping
Classic extension methods can be grouped together in static classes without regard to their underlying types. This is not the case with the type-based approach, which requires an
extension
declaration for each underlying type. Unfortunately it is also only partially the case for the member-based approach, as we saw above. Adding e.g. extension properties toMemoryExtensions
, which has a lot of open generic underlying types, would lead to it having to be broken up into severalextensions
declarations.This is an important quality of classic extension methods that unfortunately neither approach is able to fully bring forward.
Non-extension members
Current static classes can of course have non-extension static members, and it is somewhat common for those to co-exist with extension methods.
In the member-based approach a similar thing should be easy to allow. Since the extension members have special syntactic elements, ordinary static members wouldn't conflict.
In the type-based approach, ordinary member syntax introduces extension members! So if we want non-extension members that would have to be accommodated specially somehow.
Interface implementation
The type-based syntax lends itself to a future where extensions implement interfaces on behalf of underlying types.
For the member-based syntax that would require more design.
Summary
All in all, both approaches have some challenges. The member-based approach struggles with open generic underlying types, which are fairly common. They can be addressed in two different ways, both of which add significant syntax and complexity.
The type-based approach abstracts away parameter details that are occasionally useful or even critical, and would need to be augmented with ways to "open the lid" to bring that expressiveness forward from classic extension methods when needed.