Why do auto properties exist in C#?

Asked

Viewed 138 times

6

I have a doubt, because in C# there are auto properties that are usually used like this:

public double price {get; private set;}

and because she’s a public she can be accessed directly and on top I can’t differentiate that I’m changing her by a function Set or Get, or much less having a name other than the normal attribute, for example:

public double Price
{
   get {return _price;}
   set {_price = value}
}

What is their real need?

  • 1

    Could you be a little clearer about what you’re trying to ask?

  • I think you’re referring to some shortcuts in the visual studio prop + tab

  • basically I wanted to know the pq of using the autoproperties instead of using the standard of the other languages that is to do the get and set manually, I wanted to know what I would gain from this regarding the good practices and the maintenance of code !

  • I am sure then that was clarified with the reply of @Maniero

  • yes yes ! thank you for understanding

1 answer

7


Automatic properties are just what we call syntax sugar, that is, a way to write less code when that is the normal you will do most of the time.

The question is quite confused and so it can be inferred that you should make a lot of confusion about a lot of things. The example above is quite different from the example below, after all the above one only allows to assign values to the property in a private way, and may be only missing part of the code, but the bottom one is not exactly equal to the top one without the missing part, let’s do something more correct:

public decimal price {get; set;}

Will turn into:

private decimal price;
public decimal Price {
   get { return price; }
   set { price = value; }
}

I put in the Github for future reference.

See that I declared a camp (don’t call attribute as you’re imagining) with the guy decimal which is the suitable for monetary values. And I used the password value which is correct to be able to make the assignment on a property (in the original question was wrong).

Obviously there are several other ways to create a property, so you can’t always use the auto properties, the language gives the necessary flexibility. Which one you prefer to write?

Have you noticed that you don’t follow good practices? Actually research the term here on the site, especially my answers to see what I think of them. You can escape the curse of good practice (most prefer not, but you have the chance).

I needed to mention the various problems you have in your questions. If you want more information has been answered at:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.