Today I found out that VS offers an automatic way to define setters and getters. To make it crystal clear I have a simple class Students:
class Students
{
private string name;
private Int32 pin;
private string addres;
private int phone;
...
And when I select name and click ctrl +k, x then select C# and then propg I get:
class Students
{
private string public int MyProperty { get; private set; }
private Int32 pin;
private string addres;
private int phone;
There is obviously a problem with the code like this so I end up with :
class Students
{
private string name { get; private set; }
private Int32 pin;
private string addres;
private int phone;
My question is – is this the right way to get advantage of the VS automisation for getters and setters? What is the right syntax for setting and getting the value of name? If this code is correct is there a more elegant way to use VS to create my getters and setters instead of the one I found out?
The idea behind automatic properties is to remove the private fields entirely, and replace them with automatic properties (which have a hidden backing field).
There’s also a code snippet
That said, you should consider making get / setters public, and the usual convention is to PascalCase property names, viz.
EDIT
As per Servy’s comment, there is a growing movement toward making data-centric classes like DTO’s immutable. This would result in making the setters private, and providing an initialization constructor and / or class factory method to the class. But that is something for later 🙂