Daily Knowledge Drop
The current convention/standard/best practice when it comes to naming private fields on a class, is to prefix the name with an underscore. Turns out, that this convention is all due to a misunderstanding
!
Explained
In version 1.0 of the C# language specification, there was a reference to this
and underscore
. From page 213 of the spec:
public class Nested {
C this_c;
public Nested(C c) {
this_c = c;
}
public void G() {
Console.WriteLine(this_c.i);
}
}
At the time, C# didn't have the ability to uniquely identify private class members, so the initial convention was this_privateMember
, as seen on line 2, 4 and 7.
Over time as the language evolved, the this
portion was dropped, and _privateMember
was being used. No real reason for this, apart from a misunderstanding by some in thinking that the underscore was the main key in identifying a private class member.
Over time, this has been widely adopted and is now the convention - but in reality the underscore was just used as a separator between this
and the privateMember
, to uniquely identify the variable as private.
Notes
Although the convention may have it roots in a misunderstanding, I still prefer it over using this.privateMember
(or any other convention), so will continue to prefix my private variables with underscore.
References
Github Issue
C# 1.0 specification
Daily Drop 31: 15-03-2022
At the start of 2022 I set myself the goal of learning one new coding related piece of knowledge a day.
It could be anything - some.NET / C# functionality I wasn't aware of, a design practice, a cool new coding technique, or just something I find interesting. It could be something I knew at one point but had forgotten, or something completely new, which I may or may never actually use.
The Daily Drop is a record of these pieces of knowledge - writing about and summarizing them helps re-enforce the information for myself, as well as potentially helps others learn something new as well.On This Page