-
Well, I know why 'property or indexers may not be passed as ref parameter', yes, because they are actually methods under the hood. But consider this:
This is what a very innocent CLR property look like, without syntactic sugar. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
What would the compiler do in this case: object WeirdProperty
{
get { return "howdy"; }
set { SetFoo(IsFrobbled(value) ? SomeOtherProperty : someField + anotherField); }
} especially when it might not even have the source available. It might have to decompile a property's accessors and somehow find out whether there is a mapping to exactly one backing field. Properties are not required to have a backing field, or they might be several. Simply put, properties are not fields, and attempting to treat them as such isn't a good idea IMO. |
Beta Was this translation helpful? Give feedback.
-
If you want to be able to get a reference to a member, you can either use a field, or a public string Name;
// OR
private string _name;
public ref string Name => ref _name; The important thing about properties is that they hide their implementation details, which means the implementation of the property can change and the code that's using the property won't be able to tell the difference. If you were able to get a reference for any auto-property, then changing that property to some other implementation would become a breaking change. |
Beta Was this translation helpful? Give feedback.
-
Beta Was this translation helpful? Give feedback.
What would the compiler do in this case:
especially when it might not even have the source available. It might have to decompile a property's accessors and somehow find out whether there is a mapping to exactly one backing field.
Properties are not required to have a backing field, or they might be several. Simply put, properties are not fields, and attempting to treat them as such isn't a good idea IMO.