I would like to know the use of set and get properties in c#.net and how you use it with databases;
please demonstrate with examples
donwany
What is the use of get and set properties in c#
1 Answer
Know the answer? Post it. Somebody with the same question will find it here.
Aimee jacobs4 pointsPosted Jan 16, 2009, 10:37 PM EST
public, you can control what data goes into them, and how the data is
returned. For example, on the set property, you can validate the data and
return an error if it isn't valid. So if you have a State property on an
address object, you can make sure that it's one of 51 valid entries. Or you
can make sure a string will fit into a database field before you allow it to
be stuck into the field, so you always know the object is valid.
Here's one that might make more sense. It's just a simple example:
public class Circle
{
private float centerPoint;
private float radius;
public float Diameter
{
get { return radius * 2.0; }
}
public float Circumference
{
get { return 2.0 * Math.Pi * radius; }
}
public void Draw Circle()
{
//Draw circle to some object
}
public float Radius
{
get { return radius; }
set {
if( value > 0.0)
{
radius = value;
DrawCircle();
}
else
{
throw new Exception ("Invalid radius.");
}
}
}