4

Possible Duplicate:
Why use getters and setters?

In C#(ASP.NET) we use getter and setter methods to set properties of private variables but same thing can be done if we declare that variable as public. Because at one end we are restricting user from accessing that variable by declaring it as private and on other end we are allowing user to access those properties by using getter and setter properties. I can't understand its significance.

Community
  • 1
  • 1
Microsoft Developer
  • 5,229
  • 22
  • 93
  • 142
  • See also http://stackoverflow.com/questions/1568091/why-use-getters-and-setters – Scott C Wilson Jul 19 '11 at 10:04
  • 1
    To control modification of a variable of one class in another class, By making the variable private we can control the way value gets modified , For example if in another class if the variable gets modified to negative using a setter we can throw an exception to not set to negative. In doing this the variable has to be turned into private , and to access that private variable we can use getter. – karthik gorijavolu Jan 11 '18 at 03:40

3 Answers3

4

by using getter and setter you hide the internal implementation of your class. which means in the set method of a setter, you can run a whole algorithm to parse the input data into your internal data structure. you'll be able to later change your implementation without any impact to your users.

now if you expose your internal members as public, you can't hide them anymore, and any change you make to your class internal definition will probably break the user usage.

NirMH
  • 4,769
  • 3
  • 44
  • 69
4

In C#, the preferred method is to use Properties.

The advantage of this is that it exposes a convenient way of getting (or setting) data, but without exposing implemention details of the class.

A Property, or a getter or setter, can implement additional logic, for example:

  • Calculating a value based on some private data (rather than just returning a value directly)
  • Checking and validating data provided (to prevent overflows or out of range input).

By doing this you seperate the interface to your class from the implementation, allowing you easily to change the way your code works internally from how it is publicly accessed.

xan
  • 7,440
  • 8
  • 43
  • 65
0

Because it allows you to override those properties in inherited classes, add validation / INotifyProperty changed handlers at a later date, and preserves binary compatibility between versions

Bob Vale
  • 18,094
  • 1
  • 42
  • 49