[API Proposal]: Why can't access a constructor element using 'this' #7715
-
Background and motivationhttps://sharplab.io/#gist:5ec979cc565a8a49ed04f005f260c7e1 API Proposal class One(string one)
{
public void Start()
{
Console.WriteLine(one);
//Console.WriteLine(this.one); //error
}
} API UsageAlternative DesignsRisks |
Beta Was this translation helpful? Give feedback.
Replies: 12 comments 32 replies
-
Because they are parameters, not instance members:
|
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
-
And I understood that the studio somehow magically replaces these symbols <> with others. Why is it done this way? |
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
-
The existence of a field is an implementation detail that the C# compiler can choose. The names are chosen to intentionally not collide with something a user can enter. https://devblogs.microsoft.com/dotnet/check-out-csharp-12-preview/
Many C# features are implemented this way. If you add a field with a same name, one will shadow the other. References to |
Beta Was this translation helpful? Give feedback.
-
It's easier to simply restrict the user from entering a field identical to the primer in the constructor; it will help avoid potential issues |
Beta Was this translation helpful? Give feedback.
-
Such code becomes very difficult to read
|
Beta Was this translation helpful? Give feedback.
-
https://sharplab.io/#gist:a276efd01fb71475706fed5a53d63462 |
Beta Was this translation helpful? Give feedback.
-
Primary constructor parameters are not members/fields, nor can they be accessed as members/fields. If they are used beyond the lifecycle of the constructor then they are captured, but how they are captured is an implementation detail. The fact that the implementation detail might use fields as storage isn't relevant to the language. This behavior is intentional. |
Beta Was this translation helpful? Give feedback.
-
https://sharplab.io/#gist:1233568c9eea11dc36412dfdcb090d3e |
Beta Was this translation helpful? Give feedback.
Because they are parameters, not instance members:
https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/tutorials/primary-constructors#primary-constructors