-1

Suppose I have a property in a class as in the following:

class testclass
{

public string Name {get; set;}
public void dosomething(){//...}

}

There is no functional difference between this format and the following:

class testclass
{

public string name;
public void dosomething(){//...}

}

Both name fields can be set to anything including an empty string and both can retrieve just without any restrictions. So what is the use of the property semantics detailed above where there is no validation or other process in the get and set methods? One use I see is that you can remove either the get or set method to make it write only or read only, respectively. I don't know what other use this would serve.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
Helix
  • 59
  • 1
  • 8

1 Answers1

0

The main reason is so that you can change the implementation later without breaking client code. You might not do any validation or raise an event now but what if you decide to in the future? Also, properties can be bound while fields can't.

jmcilhinney
  • 50,448
  • 5
  • 26
  • 46