Extension indexers #9855
Replies: 3 comments 5 replies
-
|
I'd be interested in extension conversion operators. A use case is creating a conversion operator to or from |
Beta Was this translation helpful? Give feedback.
-
|
I second the need for conversion operators - both implicit and explicit, but especially implicit ones! This was the main reason I was looking forward to extension members. Hopefully you can add them in C# 15. This is especially useful if you are dealing with some 3rd-party library type often and have a need to use it (convert it) to one of your own types or BCL's many times. Implicit conversion operator would be ideal in such a case, as you cannot add an operator to a 3rd-party type from another library. |
Beta Was this translation helpful? Give feedback.
-
|
How about adding extension constructors and extension events as well? As for extension constructors, it can be used for creating some classes that have required members without a constructor, so that for an existing class: class Foo
{
public required int A { get; init; }
public required string B { get; init; }
}I can use extension to create a constructor for extension (Foo)
{
[SetsRequiredMembers]
public Foo(int a, string b)
{
this.A = a;
this.B = b;
}
}Then I can write With extension constructors I can even create constructors for some specified generic instantiations. For example, if I only want to allow extension<T>(NumberComparer<T>) where T : IFloatingPoint<T>
{
public NumberComparer(T epsilon)
{
...
}
}so that only for types like And for extension events, it's helpful when you want to extend a new kind of event for an existing control, and use it as an event filter for convenience: extension (ItemsControl ic)
{
public event EventHandler<ClickedEventArgs> OnDoubleClicked
{
add => ic.OnClicked += (sender, args) => { if (args.Kind == ClickedKind.DoubleClick) value(sender, args); }
remove => ...;
}
} |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Extension indexers didn't make it into C# 14.
There are probably some other member kinds that we'll consider in C# 15 as well (const).
Championed proposal: #9856
Beta Was this translation helpful? Give feedback.
All reactions