This post isn't meant to start one of those good-old-fashioned-programmer-discussion-wars. Standards and/or Best Practices when dealing with class member variables.
I know some developers out there don't like to prefix class member variables because they think it's a holdover from long ago developers. I know developers who state you must use just _ or m_. I know developers who state you must use pascalCase.
Taking a fresh look at it: Looking at “Auto-Implemented Properties” (automatic properties), is this argument dead?
Start VS.Net. Create a class. Type prop - - hit tab twice – magic of VS will fill in the properties. Looking at a sample Person class:
Add a method. Old arguments stated that _ was necessary to avoid using “this.”… gone. Old argument stated if using camel case – hard to tell what was parameter – property – class member variable… gone.
When the C# compiler encounters an empty get/set property implementation like above, it will now automatically generate a private class member variable for you within your class, and implement a public getter and setter property implementation to it. The benefit of this is that from a type-contract perspective, the class looks exactly like it did with our more verbose implementation (shown later).
Making it more concise - DRY? With the C# compiler you can now take advantage of a great language feature called "object Initializers" that allows code like:
Person p = new Person { FirstName = "Brian", LastName = "Carter" };
Object Initializers are great, and make it much easier to concisely add objects to collections. For example, if I wanted to add a person to a generics-based List collection of type "Person", I could write the below code:
List<Person> people = new List<Person>();
people.Add( new Person { FirstName = "Brian", LastName = "Carter"} );
The C# compiler allows you to go even further and also supports "collection initializers" that allow us to avoid having multiple Add statements, very DRY:
List<Person> people = new List<Person> {
new Person { FirstName = "Brian", LastName = "Carter" },
new Person { FirstName = "Dev", LastName = "X" } };
So there you have it. One may ask, how did Microsoft implement the private class members variables for you? Did they use _ behind the scenes? Next post I will dig into the dll and see.
----------------------------------
Some thoughts around old arguments:
Camel case or underscore?
View from drop downs:
Views from the class:
Should we even be concerned any longer?