Relax 'this' keyword restriction in field initializers #6128
Replies: 4 comments 16 replies
-
IIRC it's the runtime that forbids accessing |
Beta Was this translation helpful? Give feedback.
-
Definitely an interesting possibility. |
Beta Was this translation helpful? Give feedback.
-
Some other discussions I found which are related: Along with allowing to access other fields in field initializers, I think it should also be allowed to access other fields when calling other constructors, like this: |
Beta Was this translation helpful? Give feedback.
-
I come across this issue relatively often with primary constructors, as there is no way to store a temporary value as part of a computation from a constructor parameter. Wanting to set two fields to the same value as a result of an operation in the constructor. For instance: public class SomeService(TimeProvider timeProvider)
{
private readonly DateTimeOffset StartTime = timeProvider.GetUtcNow();
private DateTimeOffset TimeEventLastSeen = StartTime;
} Lexical order, not across files sounds like a very intuitive way of relaxing this restriction. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Is it possible to allow accessing other fields within field initializers, using
this
?Calling methods (and properties) would still be prohibited, only field access would be allowed. I think it should work because similar access is allowed in static context:
Beta Was this translation helpful? Give feedback.
All reactions