Syntax to extend a type by an Interface #9269
-
Today we can extend a type by an method. But as far as I know one can not extend a type by an implementation of an interface. This limits the use to interfaces to only those that have been envisioned during the design of the type (just like virtual methods). Example:
Now this could be handy to implement routines without the need to provide lambda functions or projection (select), e.g. Sum
Today we can not create a derived type of string, int or decimal as they are sealed to implement an interface that is not part of these types.
Keyword usage:
Having such a syntax would allow to move all the interface implementations from the classes to one central extension class for a specific interface. With the interface extension this would work: I hope this is a good idea - let me know in the comments. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
There are proposals underway to completely change how extensions work in C#, including support for more members and possibly (eventually) extension implementation. See #8696 This is purely hypothetical given the current syntax design, but it could end up looking something like this: public static class ListExtensions {
// make a List<T> of disposables also be disposable
extension<T> (List<T> list) : IDisposable
where T : IDisposable {
public void Dispose() {
// dispose every item in the list
foreach (T item in list) item.Dispose();
}
}
} |
Beta Was this translation helpful? Give feedback.
There are proposals underway to completely change how extensions work in C#, including support for more members and possibly (eventually) extension implementation.
See #8696
This is purely hypothetical given the current syntax design, but it could end up looking something like this: