Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why to use getter and setter methods to set class properties? [duplicate]

Tags:

c#

asp.net

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.

like image 468
Microsoft Developer Avatar asked Oct 23 '25 14:10

Microsoft Developer


1 Answers

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.

like image 131
NirMH Avatar answered Oct 26 '25 05:10

NirMH



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!