Add Extension Properties #5811
-
BackgroundC# already supports extension methods which allow for extending existing objects without altering the core contract/shape in any way, which provides a lot of benefit in when trying to add helper, convention, fluent style additions to a given type. So given the existing use cases for extension methods, there is a scenario where you may want to create getter/setter style properties for an object to make it easier to interact with, but currently the only avenue to do this is via extension methods, like so: // Some class from another assembly we do not own
public class Player
{
public Dictionary<int,int> Stats {get;}
}
// Extenstion method in our project
public static class PlayerExtensions
{
public static int Health(this Player player) => player.Stats[StatTypes.Health];
public static void Health(this Player player, int value) => player.Stats[StatTypes.Health] = value;
}
// Usage
var health = somePlayer.Health(); // Getter
somePlayer.Health(100); // Setter So as you can see we can already express the getter/setter like behaviour by explicit methods but it would be good if there was a way to express this as a fully fledged Possible Syntax To Achieve ThisDo not take this as a definitive "this is how it should be implemented" as I do not know enough about the underlying language and compiler, but this is a stab at trying to impart the high level use case. public static class PlayerExtensions
{
public static get int Health(this Player player) => player.Stats[StatTypes.Health];
public static set void Health(this Player player, int value) => player.Stats[StatTypes.Health] = value;
}
// Usage
var health = somePlayer.Health; // Getter
somePlayer.Health = 100; // Setter This would potentially also allow other operators to be used on the properties making them more useful than the explicit method approach we have at the moment. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 16 replies
-
See: #5498 dotnet/roslyn#11159 The team is exploring syntax like the following which would enable any kind of extension member: public extension PlayerExtensions of Player {
public int Health {
get => this.Stats[StatTypes.Health];
set => this.stats[StatTypes.Health] = value;
}
} The exact syntax/keywords for declaring the extension is still up for discussion. |
Beta Was this translation helpful? Give feedback.
-
Would be really helpful |
Beta Was this translation helpful? Give feedback.
-
Bump. My vote here, for this. |
Beta Was this translation helpful? Give feedback.
See: #5498 dotnet/roslyn#11159
The team is exploring syntax like the following which would enable any kind of extension member:
The exact syntax/keywords for declaring the extension is still up for discussion.