Skip to content

What is the use of get and set properties in c#

theo philus

Asked Jan 16, 2009, 11:07 AM EST1 answer
Share
LinkedInX
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

1 Answer

Know the answer? Post it. Somebody with the same question will find it here.

  • 0
    By using the properties, as opposed to making the variables they access
    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.");
    }
    }
    }
    0