[Proposal]: 'Property' Type to Enable Passing Properties with Getter/Setter #9340
Replies: 3 comments 9 replies
-
Beta Was this translation helpful? Give feedback.
-
I actually don't see much need for this special type handling. Today you can write: using System;
Property<int> prop = new(() => App.Something, (v) => App.Something = v);
Console.WriteLine(prop.Value);
class App
{
public static int Something
{
get; set;
}
}
public readonly record struct Property<T>(Func<T> Getter, Action<T>? Setter)
{
public T Value
{
get => Getter();
set => Setter?.Invoke(value);
}
} The only point I see is, that it would be great if we could bind So we could write: |
Beta Was this translation helpful? Give feedback.
-
As nice as this proposal is, it's definitely in the realm of source generators. However: what happens if the setter isn't Test t = new(42);
// If `p.Setter` null? I'd assume yes.
Property<int> p = propof(t.Value);
public sealed class Test(int value)
{
public int Value { get; private set; } = value;
public void DoThing()
{
// Is `p.Setter` null?
Property<int> p = propof(this.Value);
}
} For Test t = new(42);
Property<int> p1 = propof(t.Value); // `p.Setter` is null
Property<int> p2 = t.GetProperty(); // `p.Setter` isn't null?
public sealed class Test(int value)
{
public int Value { get; private set; } = value;
public Property<int> GetProperty() =>
propof(this.Value);
} While arguably sound — it's the same as if you manually did |
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.
-
Summary
A structure that holds the getter and setter of a property, which any property can implicitly cast to it.
Property Type
Imagine a structure that represents a 'property instance', which holds its getter and setter, allowing you to assign a property to it.
You could implicitly cast any property to this structure:
This could lower to:
With this, developers could easily pass any property 'by reference' as a parameter or even use extension methods.
The compiler would need to recognize the
Property<T>
type, so it could prioritize it over the actual value type of the property when deciding on extension overloads.This would allow developers to write:
or, using an extension method:
Instead of the more verbose:
It's annoying when you have to pass two different version of
label.Width
, which breaks the purpose of property.Additional Syntax Sugar
This approach is already quite useful, but if new syntax sugars can be expected, then we can make use of some new keywords. For instance, introducing keywords like
propin
andpropout
to represent the getter and setter of a property in function parameter modifiers.For example:
This could lower to:
At the caller side:
This could lower to:
And we may finally be able to do things like this:
Beta Was this translation helpful? Give feedback.
All reactions