class point
    {
        private double pi;
        public double PI
        {
            get{ return pi; }
            set{ pi = value;}
        }
     }
    
    class Program
    {
        static void Main(string[] args)
        {
            point p1=new point();
            p1.PI = 3.14;            
            Console.WriteLine("The value is {0}",p1.PI);
            Console.ReadLine();
        }
    }

Actually i couldn't understand the use of PROPERTIES concept....
Here i used Two variables rather than using one variable... It's simply leads to more memory consumption.... Then what is the real benefit behind the PROPERTIES concept... ?
Somebody says that,it provides security,but here still anyone can edit the value of PI. Then how we can say it as a secured one....

Recommended Answers

All 3 Replies

It's simply leads to more memory consumption....

Properties don't consume memory in the object, they're a form of method that acts like a field.

Somebody says that,it provides security,but here still anyone can edit the value of PI. Then how we can say it as a secured one....

If you write properties that expose fields completely then there's no security benefit over public fields. However, consider this modified property:

public double PI {
    get {
        if (!_piGenerated) {
            _pi = GeneratePi(_piPrecision);
            _piGenerated = true;
        }

        return _pi;
    }

    private set { _pi = value; }
}

Now the set isn't accessible outside of the class, and the get performs some internal logic that doesn't matter to users of the property. This is the power of properties, you can get method-like behavior with field-like syntax.

1-actually you used single variable and two methods
2-the main usage is validation
Ex:

class myCustomInt
{
         int minVal,maxVal;
         int _CurrVal;
         public int CurrVal
         {
         get {return _CurrVal;}
         set 
         {
                  if(value>=minVal &&value<=maxVal)
                   _CurrVal=value;
         }

         }
         public myCustomInt(int ValidMax,int ValidMin)
         {
                  minVal=ValidMin;
                  maxVal=ValidMax;
                  _CurrVal=ValidMin;
         }

}

In the new C# you can make fields into automatic properties, and apply public/private/protected/internal/etc accessors to them:

int myInt { public get; protected set; }

Pretty sweet imo. Really not sure how much overhead is involved in doing this though...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.