Add an operator for creating a delegate-like object from a property #9580
Unanswered
timojch
asked this question in
Language Ideas
Replies: 1 comment 1 reply
-
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Abstract
C# has a
typeof
operator, which takes a type name as a symbol and returns the correspondingSystem.Type
object.I propose a similar operator which accesses the reflection of properties and fields, and returns an object similar to a
delegate
, but for properties instead of methods.Definition
Consider the following
InstanceProperty
classIt can be used like so:
This proposal is to add a
reflectof
operator which generates a binding which can be used in an identical way.What would this be used for?
The two primary use cases I see for this are for UI property bindings (e.g. binding a UI checkbox to a bool value in the underlying model) and animations (e.g. creating a tween object which changes the value of a property over time).
Why a new operator?
Having a built-in
InstanceProperty
class and areflectof
operator to create them would have the following advantages:Compile-time type-checking
In the examples above, three things are currently checked at runtime which could be checked at compile-time:
propertyName
inInstanceProperty
's constructor corresponds to a name of actual property (currently checked during construction).IsFoo
onExampleObject
is abool
(currently checked when unboxing the value fromobject
inside ofPropertyInfo.SetValue
)IsFoo
is not read-only.We also would be able to avoid taking generic arguments, which would make the code easier to modify. For example, changing
ExampleObject.IsReadOnly from a
boolto another type that
bool` can be assigned into would not require any changes to the code which binds to it.Performance
There are currently two areas where the existing reflection-based approach potentially loses quite a bit of performance:
PropertyInfo.SetValue
requires boxing the value to an object and back, which results in a runtime type check before the value is assigned. This feature would allow the type-check to be performed at compile time, and the object could be stored in its original form all the way through.It's possible to write code that doesn't have these disadvantages, but only by not using reflection, and instead writing unique code for each property that is bound to.
Beta Was this translation helpful? Give feedback.
All reactions