I am the new to the programming and now I have a query regarding the variable and properties which is "what is the difference between declaring public variable and public properties?". Could anyone explain me with some instances?
-
Is there a particular language you are referring to? – Adam Reed Mar 13 '12 at 07:11
-
http://stackoverflow.com/questions/379041/what-is-the-best-practice-for-using-public-fields and countless others, search "public field vs property" or anything along those lines – Henry Mar 13 '12 at 07:11
-
@Adam Reed I am using C# – Krish KC Mar 13 '12 at 07:35
2 Answers
Alot of people have different views on what is the "right" way, just different coding standards. Personally i think public properties give you a little more control as in you can have some simple logic in the get or set methods. Where as public properties are fine if you just want some quick global variable.
There are some instances in .net when you have to have properties rather than public variables e.g. usually when binding to datasources etc.
for more info check this link:

- 3,512
- 2
- 36
- 53
To clarify a little of what John said, properties allow you to add limitations and logic to what you are doing.
For instance if I have a rectangle class
class Rectangle
{
private float mWidth;
private float mHeight;
private float mArea;
public float width
{
get
{
return mWidth;
}
set
{
mWidth = value;
mArea = mHeight*mWidth;
}
}
public float height
{
get
{
return mHeight;
}
set
{
mHeight = value;
mArea = mHeight*mWidth;
}
}
public float area()
{
return mArea;
}
}
So rect.width += 20; will update both the width and area;
Obviously this is a dumb example, but you could have done this without the properties for width and height, using public variables instead and instead just used
public float area
{
get
{
return width*height;
}
}
This will give you the correct area if you say float x = rect.area, but will not let you say something like rect.area = 40.
There are many more in depth things that you can do with properties, like databinding, for instance, but if you are just starting to program, you will get to this later.
For right now, you can treat a property as a convenient method that does not require () and that can take or give a variable.
If it is doing nothing but getting and setting, its probably better off as a variable.
If it is doing alot of internal work, and affect a considerable portion of your class, it should probably be a method.
If it is a quick function to validate input (float rotation{set{mRotation = value%360;}}) or a multiple check output ( bool isInMotion{get{return (!isTurning && ! isMoving)}} propertys work well.
No rules are final of course.
I hope this gives you a basic understanding of properties vs variables, though as always there is plenty more to learn.
Good Luck!

- 3,294
- 2
- 15
- 15