Proposal: Implicit cast from property expression to get/set delegate? #8743
Replies: 4 comments
-
I would love this! I think it's been suggested before to use the syntax |
Beta Was this translation helpful? Give feedback.
-
A similar proposal for events: https://github.com/dotnet/roslyn/issues/298. I agree that something like And the same issue applies to |
Beta Was this translation helpful? Give feedback.
-
I like the general idea, but that particular syntax would run into issues here: class Foo {
Action<int> ExampleProperty {get; set;}
public Foo(Action<int> prop) {
ExampleProperty = prop;
}
public void Bar(Action<int> action) {
action.Invoke(5);
}
// ...
}
// ...
Foo f = new Foo(x => Console.WriteLine(x));
f.ExampleProperty.Invoke(5); // Does this throw an error?
f.Bar(f.ExampleProperty); // Does this throw an error? |
Beta Was this translation helpful? Give feedback.
-
I tried this out with expression trees to see how it's handled already: static void Thing(Func<int> func);
static void Thing(Expression<Func<int>> exp);
static void Main(string[] args)
{
Func<int> func = () => 15; // the duality is fine here
Expression<Func<int>> exp = () => 15; // the duality is fine here
Thing(() => 15); // but this is an "ambiguous" error
} @svick: The duality of the notation doesn't seem like a problem in practice. The intent can be clear from the usage (i.e. as with the two forms of @TheUnlocked: Your two "does this throw an error?" examples:
|
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.
-
Potential use case is as follows:
And the proposal would allow this:
There's not much to this. We're just recognizing the hidden set_XXX() method behind the property and allowing the compiler to generate a delegate if the target has a matching signature.
What the compiler is actually doing:
I think there's precedent for this kind of target matching with the existing expression trees vs delegate matching for expressions etc.
This is very minor syntactic change so probably not even worth the effort. It did seem neat though. I thought I'd mention it in case any other use cases come to mind. I think it could have potential uses in "fluent" APIs, especially if the compiler could generate a specially recognised class that contains both delegates.
The compiler could potentially map SomeClass.Name etc. to a built-in class:
i.e. the signature of the fluent API's AddProperty method would be as follows:
This is a slight variant on my use case above. There would need to be both static and instance versions of this mechanic, with different delegate mappings.
Maybe even stick a PropertyInfo on there.
Just thinking out loud really. What do you think?
Beta Was this translation helpful? Give feedback.
All reactions