New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[Proposal]: Extensions #5497
Comments
I prefer using public extension Foo of int : IA, IB, IC, ...
{
...
} Otherwise it will be too confusing if you are extending an interface: public extension Foo : IA, IB, IC { } vs public extension Foo of IA : IB, IC { }
|
I'm curious as to how the team weighs the relative benefits between "roles" and "extension implementation". It feels that without some additional effort in the runtime the two are somewhat incompatible with each other, so if those differences can't be reconciled which of the features might the team lean towards? Personally, I find extension implementation much more exciting than roles, but that's just my opinion. |
@hez2010 public extension Foo for IA : IB, IC { } |
Who gave you an early preview of my notes? They're up now, discussion at #5500. |
Here's a scenario that will be great fun to try to accommodate in the design: interface IFoo { }
interface IBar { }
class Thing { }
public extension FooThing for Thing : IFoo { }
public extension BarThing for Thing : IBar { }
void Frob<T>(T t) where T : IFoo, IBar { }
Frob(new Thing()); On an unrelated bikeshedding note, what about using the existing reserved keywords |
@sab39 Given, as you've mentioned, how similar these two concepts are. I too am looking for a good syntactic way to convey that similarity, with a clear way to do indicate in which way they differ. Thanks for the |
I'm not sure if I should re-post my comments from the discussion here?
This is complicated, but doable using current constraints of the framework. An anonymous type can be generated: class <mangled>Thing_IFoo_IBar : IFoo, IBar
{
internal <mangled>Thing_IFoo_IBar(Thing thing) { this._thing = thing; }
readonly Thing _thing;
void IFoo.Foo() { ... } // these member(s) are copied from, or call into, FooThing
void IBar.Bar() { ... } // these member(s) are copied from, or call into, BarThing
}
Frob(new <mangled>Thing_IFoo_IBar(new Thing())); The same can be done for generic types, etc. Yes, it's complicated, but unlike roles, it's very possible. |
This was just one example. It's not the main motivation. We discussed in the LDM that there were definitely plenty of scenarios where you'd still want adapters in a strongly typed way that would be sensible. |
@TahirAhmadov That works, more or less, for the specific example I gave, but what if |
If it's not the main motivation, surely it shouldn't be the one discussed in the OP, should it? |
The OP is simply showing a demonstration. This is a broad topic and we need to spend a ton more time on it prior to even getting close to a place where we could write something up that was fully fleshed out and chock full of examples and whatnot. |
The |
Back with .NET Framework, I've often ran into situations where i wanted a The only thing I don't quite get is why we need two keywords here, |
That's the thing, it would be very interesting to see an example which would demonstrate how |
That's fine. It's something we're working on at this moment '-). The point was raised and was something we intend to get to and write more on. I def don't want us to get the impression that it's just for that. Thanks! |
Roles feel like they need a validator method, something that is invoked to by the "implicit conversion" to ensure that the underlying object can fill in that role. I'm not even sure the conversion should be implicit. I'm sure it will be annoying to do stuff like |
Hmm, that almost makes it sound like you want Extension DUs... |
I don't want them to be a DU per se, it's more similar to getting an |
@orthoxerox F# has a feature Partial Active Patterns which looks somewhat like your idea. |
C# isn't the only language on CoreCLR, without runtime support how would you expect roles to be defined and used in other languages? Other languages don't recognize the mangled anonymous class. |
The pseudocode I wrote was specifically for extensions, not roles. class Thing { }
interface IFoo { void Foo(); }
extension FooThing: Thing, IFoo { void Foo() { ... } }
void Frob(IFoo foo) { }
// this line:
Frob(new Thing());
// is compiled to this:
class <mangled>Thing_IFoo : IFoo
{
internal <mangled>Thing_IFoo(Thing thing) { this._thing = thing; }
readonly Thing _thing;
void IFoo.Foo() { ... } // these member(s) are copied from, or call into, FooThing
}
Frob(new <mangled>Thing_IFoo(new Thing())); |
I also want to voice that I wish there would be some keyword being reused instead of casting new keyword Or Aside from that I have nothing against, and fully support this issue |
Keywords can be introduced as contextual keywords so it can be made not to introduce breaking changes. |
@hez2010 I know there is no breaking change but it still should be the last option to introduce any new keyword. If there would be any possible for composite or reuse then we should |
I found the idea of |
I don't get why I'll just copy/paste my comment from the other post so something like this: // Customer.cs
namespace Data;
public extension Customer : DataObject // Wrapper type
{
public string Name => this["Name"].AsString();
public string Address => this["Address"].AsString();
public IEnumerable<Order> Orders => this["Orders"].AsEnumerable();
}
// JsonDataObject.cs
namespace Data;
using JsonLibrary;
public extension JsonDataObject : DataObject // Extension type
{
public string ToJson() { … this … }
public static T FromJson<T>(string json) { … }
}
// Program.cs / Main method
using Data;
using Data.JsonDataObject; // Importing a specific extension type
using Data.*; // Importing all extensions types in the namespace Data
var customer = customer.FromJson<Customer>(args[0]);
WriteLine(customer.ToJson()); |
Would this be allowed under roles? role Foo<T> : T
where T : ISomeInterface
{
} or would we be forced to directly extend the interface and bring in boxing conversions all over the place as we implicitly cast back and forth in a generic function? |
Thinking about it, I imagine this happening: class Thing { }
interface IFoo { void Foo(); }
// the following line
public extension FooThing: Thing, IFoo { void Foo() { ... } }
// is compiled to:
// these attributes are once per assembly, similar to NRT attributes
class ExtensionTypeAttribute { public ExtensionTypeAttribute(params Type[] types) { ... } ... }
class ExtensionInstanceMemberAttribute { }
class ExtensionStaticMemberAttribute { }
// the actual extension becomes:
[ExtensionType(typeof(Thing), typeof(IFoo))]
public static class FooThing
{
[ExtensionInstanceMember]
public static void Foo(Thing @this) { ... }
}
void Frob(IFoo foo) { }
// this line:
Frob(new Thing());
// is compiled to this:
class <mangled>Thing_IFoo : IFoo
{
internal <mangled>Thing_IFoo(Thing thing) { this._thing = thing; }
readonly Thing _thing;
void IFoo.Foo() { FooThing.Foo(this._thing); }
}
Frob(new <mangled>Thing_IFoo(new Thing())); |
Thanks @HaloFour for splitting off and summarizing all the detailed discussion here. Makes sense to have as a spin-off discussion and address even potentially independently from this feature. Do like the |
That seems like a pretty big hack vs. a scenario fully intended to be supported by both the language and runtime for general use. But if such a language feature can build on top of that, all the better. |
Note that mono only added support for |
Actually, if what is being discussed is just
This trick can be used to freely invoke any protected member, even virtual ones, as long as the accessor is non-virtual. Should this feature be implemented on top of that, the compiler could easily cook the However, quoting my own post from last year, I hold the opinion that encapsulation breaking should not be built into the language. If the developer wants that, it's their responsibility to use the EDIT: Just realized that @HaloFour created a separate discussion for the theme of protected member access. Should I move/copy this post into that? |
Those are just tricks, though, and there's no guarantee that they will work on any given runtime. I don't think it's safe to rely on being able to use that in general purpose libraries, especially since they do break encapsulation.
If the language were to consider something like this it should be on much tighter guardrails. The language can ensure, for example, that you can only call these members from within a protected context, so that you're not breaking encapsulation. Either way, there seems to be some desire for functionality like this, so it's worth the conversation. But I don't think it's necessarily tied to extensions, so the conversation should probably be on the other discussion. |
Can extension types be nested? extension Extension for UnderlyingType1
{
public extension PublicNestedExtension for UnderlyingType2 { }
}
class Class
{
private extension PrivateNestedExtension for UnderlyingType3 { }
}
class UnderlyingType1 { }
class UnderlyingType2 { }
class UnderlyingType3 { } I didn't see any mention of this in the proposal. |
@ds5678, I'd say that such an extension would be only usable in that class scope. |
@alfosua For implicit extension Extension for UnderlyingType1
{
public explicit extension PublicNestedExtension for UnderlyingType2 { }
}
class UnderlyingType1 { }
class UnderlyingType2 { }
var x = new UnderlyingType2();
var y = x as Extension.PublicNestedExtension; |
I have not seen this mentioned/addressed, but I might've simply missed it. As I've understood it - and correct me if I'm wrong - implicit extensions are a superset of the "old" way. With this in mind: When (if?) this launches, will there be a push to obsolete the old way? Obviously not on a language basis(backwards compatibility etc..), but in documentations and in the official libraries? Will there be a code fix to convert the old syntax to the new? Will there be analyzers (information-level probably) that "warns" you about using legacy syntax? We - as a community or even individual teams - can of course create our own, but I'm wondering about what the team thinks on the matter. |
Yes/no. This is not really a superset. Today it is fine (and a totally reasonable pattern) to have a single static class with extensions on many disparate types. In the case where you have a single static class just with extensions on a single type, we probably will have a fixer to suggest moving to the new form. We would not deprecate it remove the existing form from the language. |
That's something I didn't consider - good thing I'm not a language designer, eh? 😅 With that in mind, your plan seems to be inline with what I was hoping for! 👍 |
Is this somehow available on sharplab? I tried to use the branch on sharplab, but unfortunatley I always get an exception using System;
public class UnderlyingType {
public required string Id { get; set; }
}
explicit extension Ext1 for UnderlyingType {
public string Name { get; set; }
}
|
That is as far as has been implemented in the branch. Nothing further exists yet. |
One thing I've been wondering recently after reading it some time ago; Using explicit extensions - previously "roles" - as Typed values/Typed Ids. Which parts of this will work as expected? public explicit extension PersonId for Guid; // I'm assuming body-less will be possible.
public class Person
{
public PersonId Id { get; init; } // I'm assuming properties can be explicit extensions
}
var person1 = new Person
{
Id = Guid.NewGuid(), // I'm assuming(and hoping..) this will be a compiler error.
}
var person2 = new Person
{
Id = PersonId.NewGuid(), // I'm assuming I still have access to the underlying methods, but I'm also assuming it will still return a `Guid` Type, so we have to downcast it somehow.
}
var person3 = new Person
{
Id = (PersonId)PersonId.NewGuid(), // I'm assuming we have to do this? We could probably just make a `New()` method on `PersonId` directly though instead of this dance.
}
// ...
public interface IPersonService
{
public Person GetById(PersonId id);
public Person GetByRawGuid(Guid id);
}
IPersonService personService = ...;
PersonId personId = ...;
Guid guid = ...;
var person4 = personService.GetById(personId); // I'm assuming this will work
var person5 = personService.GetById(guid); // I'm assuming(and hoping..) this will not work for the same reason as I cannot instantiate `person1`
var person6 = personService.GetByRawGuid(personId); // I'm assuming this will work as it gets upcasted to a Guid
var person7 = personService.GetByRawGuid(guid); // This obviously works. |
It would be good if a fixer was introduced to convert existing |
Any update for 2024? |
There is an upcoming LDM meeting which will discuss extensions. |
I can't understand why #92689 was closed |
any plan for extension |
I assume you mean dotnet/runtime#92689. It was closed for the reasons cited in the comments, and has nothing to do with this issue. |
Discussed in #5496
Originally posted by MadsTorgersen November 30, 2021
Extensions
LDM Meetings
https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-12-01.md#roles-and-extensions
https://github.com/dotnet/csharplang/blob/main/meetings/2022/LDM-2022-08-31.md#roles
https://github.com/dotnet/csharplang/blob/main/meetings/2022/LDM-2022-09-26.md#roles--extensions
https://github.com/dotnet/csharplang/blob/main/meetings/2023/LDM-2023-02-22.md#extensions
https://github.com/dotnet/csharplang/blob/main/meetings/2023/LDM-2023-12-11.md#extensions
https://github.com/dotnet/csharplang/blob/main/meetings/2024/LDM-2024-02-28.md#extensions
The text was updated successfully, but these errors were encountered: