3

In c# when I always heard that is a good practice when creating a property for a class to include the get e set functions. For example:

public int Id { get; set; }

I think the reason to be a good practice is that if I want to change the behaviour I do not need to change the public interface of my class. Example:

public int Id 
{ 
   get; 
   set
   {
      if (value < 0)
         value = 0;
   }
}

My question is, if I declare my property without the get and set methods I will not get the same effect? If I declare my property like this:

public int Count;

Can I change is behaviour without change the public interface? If I get the same effect then what’s the point of creating the get and set methods by default if in 90% of the time we don’t need them?

miguelbgouveia
  • 2,963
  • 6
  • 29
  • 48
  • 7
    `public int Count;` is not a property, but a field. – Dennis_E Dec 11 '15 at 14:56
  • 4
    You are declaring [field](http://stackoverflow.com/q/295104/1997232). – Sinatr Dec 11 '15 at 14:56
  • 2
    Creating public fields removes any ability you have to validate input. So some external class can change count and the internal class has no way to know whether the count is valid or not. Using the properties lets you do validation. – Jarrett Robertson Dec 11 '15 at 14:56
  • 1
    See this: http://blogs.msdn.com/b/vbteam/archive/2009/09/04/properties-vs-fields-why-does-it-matter-jonathan-aneja.aspx – rory.ap Dec 11 '15 at 14:57
  • 2
    Whereas `public int Count { get; set; }` is an automatically-implemented property... and your initial piece of code is simply invalid. – Jon Skeet Dec 11 '15 at 14:57
  • 1
    I closed it as a duplicate, not because it is a perfect match to your question, but your question relies on a misunderstanding of properties and fields. – Patrick Hofman Dec 11 '15 at 14:59
  • 1
    See this similar thread: http://stackoverflow.com/questions/5096926/what-is-the-get-set-syntax-in-c – Manuel Dec 11 '15 at 14:59
  • 1
    @PatrickHofman -- I'm trying to find the SO resource that tells you when you can close questions without votes from others. What rep do you earn that at? – rory.ap Dec 11 '15 at 14:59
  • 1
    If you are a gold tag badge holder on the specific tag you can close as duplicate without others. – Patrick Hofman Dec 11 '15 at 14:59
  • 1
    @PatrickHofman -- Ahh, good to know, thanks. – rory.ap Dec 11 '15 at 15:00
  • 1
    @roryap http://meta.stackexchange.com/q/230865/245360 – Patrick Hofman Dec 11 '15 at 15:01

0 Answers0