-
Notifications
You must be signed in to change notification settings - Fork 1k
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
Champion "Extension function members" #192
Comments
Almost agree and totally support with a bit of arguments and concerns
/// static class cannot extend anything before so it not breaking any previous code
public static class Ext : MyStruct
{
} |
I think I'm late to the party and forgive my ignorance, but what about just supporting |
@Bartmax |
i know that, but that doesn't mean it can be "reworked" to allow classes from other assemblies hence creating extensions for arbitrary classes. |
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 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). |
Please consider this feature for the nearest releases. It would make life so much easier. |
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 |
@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). |
Well, it's 100% in the |
@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... |
@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:
|
@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 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. |
So, would this proposal cover being able to add events as an extension to an existing class as well? |
dotnet/roslyn#11159 (comment):
|
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
} |
I wanted to add one simple to understand scenario in higher level code where this would have been a great feature to have on the library level. We wanted to support SQL row value syntax in Entity Framework Core (dotnet/efcore#26822). Currently, this is the most readable C# syntax the user will have to write to represent row value: .Where(b => EF.Functions.GreaterThan(new[] { b.Column1, b.Column2 }, new[] { 1, 2 })) Not so readable. This proposal would in theory allow providing custom tuple operators and allow the user to write the following instead: .Where(b => (b.Column1, b.Column2) > (1, 2)) |
Extension properties would greatly help in dotnet/comet, which heavily uses builder pattern to create views. new ShapeView(new Circle()
.Fill(LinearGradient)
.Style(DrawingStyle.Fill)).Frame(200,100), With extensions new ShapeView(new Circle { Fill = LinearGradient, Style = DrawingStyle.Fill }) { Frame = (200, 100) },
// Frame have signature: void set_Frame(this ShapeView view, (double, double) size) new Text("TEST PADDING").Frame(height:30).Margin(top:100), With extensions new Text("TEST PADDING") { FrameHeight = 30, MarginTop = 100, }, I find extension property version more readable, especially in first case |
Extension static methods would be useful for classes in testing/mocking frameworks and elsewhere that define fluent methods hanging off a static class like |
@uecasm was just coming to call out the same thing. Being able to write extensions off of |
Is there anywhere to see if any progress is being made on this issue? |
Yup. Right here. |
Doesn't #5497 supersede this? |
That one's a non-starter for me because it requires an extra keyword/decoration on the class being extended. The whole point of extension methods is to extend things that the original designer didn't think of and didn't make extensible any other way. |
@uecasm Do you mean #5497? I think it does not… From the proposal public class DataObject
{
public DataObject this[string member] { get; set; }
public string AsString() { }
public IEnumerable<DataObject> AsEnumerable();
public int ID { get; }
} gets extended by public extension JsonDataObject : DataObject
{
public string ToJson() { … this … }
public static DataObject FromJson(string json) { … }
} I don't see any special keyword. I havn't read the howl thread, so maybe I skiped something |
Oh, maybe I overlooked something then. It looked to me like you could only extend |
No, as I understood, Roles are a construct to add Interfaces to external types (and maybe more), but are not nessesary to extend something. |
Omg, no ETA for this best feature for C#? 😞 |
What I'm hoping for with extension properties specifically is something like public static class MyStringExtensions {
public static string Author {
get(this string);
set(this string);
}
public static string Half {
get(this string baseStr) => baseStr.Substring(baseStr.Length / 2);
}
} The examples aren't stellar, but I feel like the syntax feels natural and intuitive given what devs are used to with extension methods. |
Still very much in design, but the current thought is that you declare an "extension type", which can support most members: #5497 implicit extension MyStringExtensions for string {
public string Half {
get => Substring(Length / 2);
}
} |
I still prefer classic extension syntax, but there's some problems: public extension MyGuidExtensions for System.Guid // name or qualified name
{
public string ToBase64()
{
// this = treated as Guid instance, internal/private fields should
// be visible only in same project or solution or
// else use reflection instead.
// but... "this" can be omitted? this is a good question
return Convert.ToBase64String(this.ToByteArray());
}
}
public extension DynIntExtensions for Int32 // force qualified name instead keyword?
{
public int SevenBitLength
{
get
{
int numBytes = 0;
var value = this; // make a copy from self, but how?
do
{
value >>>= 7;
numBytes++;
}
while(value > 0);
return numBytes;
}
}
}
// Sample code:
var offset = 0;
int packetId = reader.ReadVarInt32();
var bytesToSkip = packetId.SevenBitLength;
offset += bytesToSkip Or something similar to what the Rust language does with the |
@nathan130200 i'm not quite certain i'm getting what the problems are that you're referring to. |
I would expect that you could use the name (or alias) of any type in scope, including the keywords for the primitive types like
My gut feeling is that within an "extension" type that
If the above is true, then I would expect that this would just work. These are good questions for the extensions working group. |
It's not really a problem but the comments I put in the code. Some things don't seem so objective. For example, "this being treated as an instance of Guid".
So in this case, the compiler could understand that if we are inside the extension, it will treat Or better yet, add a keywork called I think that these extensions are just a way of instructing the compilation and not a class in itself. Because what happens if you want to cast the extension? I don't think it would make sense to cast to a type that doesn't actually inherit, it's just "inheritance" at runtime, I think that's the right word. I think that these extensions are just a way of instructing the compiler/IDE and not a class in itself. Because what happens if you want to cast the extension? I don't think it would make sense to cast to a type that doesn't actually inherit, it's just "inheritance" at runtime, I think that's the right word. Ah, unless it is implemented, there is some way to do an implicit/explicit cast for the extension. |
I'm not seeing the issue. Why would that not be hte case?
I don't see the value of that. if
Neither? The extension is just a set of members on a particular type. That partial type can be any type (unless we choose to limit choices there in some fashion). It's like asking "is an extension method a reference or value type?". It's neither. It's a method. An "extension" then is just a collection of those members (all extending a particular type), and it's not limited to just methods. It can be things like constructors, properties, etc. |
As an example, ignoring that your code has a property, you could imagine that:
Is just shorthand for: public static class DynIntExtensions
{
public int GetSevenBitLength(this int @this)
{
int numBytes = 0;
var value = @this;
do
{
value >>>= 7;
numBytes++;
}
while(value > 0);
return numBytes;
}
} All that 'implicit extensions' (as a feature) is doing is:
|
What could be done in this case is:
In the case of fields, events and properties, perhaps an attribute that makes the compiler identify that that extension "method" can be invoked as a member. Just like you used |
You can't do extension fields as extensions have no way to add state to anything. |
They can. |
That's what an extension already does. See how extension methods are encoded into a dll. It's just an attribute that marks then as such. |
We don't need that in source as the source already indicates this by use of the |
The "workaround" would be an extension property returning a ref-value, which is "almost as good" as a field. It can lookup or create a container based on the instance so it has someplace to store the data, e.g. a ConditionalWeakTable, and then can return a reference into that data container. |
See also dotnet/roslyn#11159
The text was updated successfully, but these errors were encountered: