locked
Properties in C# RRS feed

  • Question

  • Hi All,

     

    I really have a doubt regarding use of property in C#.

     

    My question is: Can we have private properties inside a class?

    If yes, then please let me know what is the use of private propertise in a class.

     

    Thanks and Regards,

    ChatanyA Agrawal

    Friday, February 9, 2007 12:56 PM

Answers

  • Of course that you can have private properties. Properties have many purposes, not just to be interface to some private value. Sometime you want to have a property which will show some value or group of value in different format or type. Sometime you need to execute some code in property setter. So when you want to achive this, you use properties, and does some property is public or private is just a meter of accessibility and security.
    Friday, February 9, 2007 1:18 PM
  • Hi, Chatanya

    Usually, we use properties to get some info about the class from outside, in this case we use public or protected.

    Also, abstractly we can free modify properties as private, if we use them inside the class.

    Thanks

    Monday, February 12, 2007 2:24 AM
  • You are allowed to have private properties.  Typically, for my own private members I do not write properties, but there's no really good reason not to that I can think of. 

    After all, we make public properties to hide the details, so that if we want to do any bounds checking, filtering or such we can provide it in the property in one place, which greatly aids with code maintenance.  (In fact, I would go so far as to say that NONE of our member variables should ever be public, and that we should ALWAYS use properties for them... but that's a question we all have to deal with on our own.)

    The very first "Item" in the book "Effective C#" claims we should always use properties for a variety of reaons.  I'll give just one here:

    Quote from the book: Because properties are implemented with methods, adding multi-threaded support is easier. Simply enhance the implementation of the get and set methods to provide synchronized access to the data:

    public string Name

    {

    get { lock (this) { return _name; } }

    set { lock (this) { _name = value; } }

    }

    So will i start making private members properties?  Probably not today as a rule, but I might be sorry some day.  Bill Wagner's book has a lot more reasons why we should always use properites.

     

     

    Tuesday, February 13, 2007 12:18 AM

All replies

  • Of course that you can have private properties. Properties have many purposes, not just to be interface to some private value. Sometime you want to have a property which will show some value or group of value in different format or type. Sometime you need to execute some code in property setter. So when you want to achive this, you use properties, and does some property is public or private is just a meter of accessibility and security.
    Friday, February 9, 2007 1:18 PM
  • Hi Boban,

    Thanks for your reply.

    But I am intrested to know what is the use of private property as we have function to achieve same thing. In which case I really need private properties?

    Thanks and Regards,

    ChatanYA Agrawal

    Friday, February 9, 2007 1:28 PM
  • Properties are in fact methods for get and set accessors, and nothing more. I personaly preffer properties, but of course i don't use them always. I have more offen internal properties then private but maybe because i was in such situations. Small number of developers say that they don't need properties like in old days, but bigger part of them want them and want every way of extensibility around them like this having private properties, like having public getter and protected setter.
    Friday, February 9, 2007 1:52 PM
  • One place I like using private properties is when I have a variable that needs to be cast to a specific type every time I refer to it.

    For example:

    // I know for certain that myBrush is always a SolidBrush.  But for extensibility purposes,
    // I'll refer to it as 'Brush'.

    private Brush myBrush;

    // Now I create a private property that allows me to always access
    // the brush as a SolidBrush, so that I don't have to dirty my code with tons of casts:
    private SolidBrush MyBrush
    {
    get { return myBrush as SolidBrush; }
    }

    // Then in my code:
    this.MyBrush.Color = whatever....

    This is usually useful when I have a base class that I have several different objects deriving from.  It allows me to put basic implementation in the base class, enough to simplify the child classes, without locking down the child classes to specific objects.
    Saturday, February 10, 2007 4:42 AM
  •  

    By using a Property you dont need to create two different methods to set a value and another to retrieve a value.

    In a single property, with the same name you can get and set. Although this can also be achieved through an overloaded method.

    You have a very good question as to Why use private properties.

    Consider this:

    private int Kilogms {

         set {

                  grams= 1000*value;

                  kilogms = value;

          }

         get { return kilogms; }

    }

    private int Grams {

         set {

                  grams= value;

                  kilogms = value / 1000;

          }

         get { return grams; }

    }

     

    If I want that each time I set Grams or Kilogms the other unit should also get the value, then i can use the above property. And if I dont want any other class to use them i make them private.

    Again, this can also be done using overloaded methods, but a property would be simpler and can be used like:

    Kilogms = 50;

    this will set kilogrms = 50 and grams = 50000

     

    I hope this was useful to you.

    Regards

    Saturday, February 10, 2007 9:21 AM
  • Hi, Chatanya

    Usually, we use properties to get some info about the class from outside, in this case we use public or protected.

    Also, abstractly we can free modify properties as private, if we use them inside the class.

    Thanks

    Monday, February 12, 2007 2:24 AM
  • Imho the advantage of properties is that they allow you to silently replace a class variable with a function...
    Monday, February 12, 2007 7:20 AM
  • You are allowed to have private properties.  Typically, for my own private members I do not write properties, but there's no really good reason not to that I can think of. 

    After all, we make public properties to hide the details, so that if we want to do any bounds checking, filtering or such we can provide it in the property in one place, which greatly aids with code maintenance.  (In fact, I would go so far as to say that NONE of our member variables should ever be public, and that we should ALWAYS use properties for them... but that's a question we all have to deal with on our own.)

    The very first "Item" in the book "Effective C#" claims we should always use properties for a variety of reaons.  I'll give just one here:

    Quote from the book: Because properties are implemented with methods, adding multi-threaded support is easier. Simply enhance the implementation of the get and set methods to provide synchronized access to the data:

    public string Name

    {

    get { lock (this) { return _name; } }

    set { lock (this) { _name = value; } }

    }

    So will i start making private members properties?  Probably not today as a rule, but I might be sorry some day.  Bill Wagner's book has a lot more reasons why we should always use properites.

     

     

    Tuesday, February 13, 2007 12:18 AM
  • Your example with the 'thread-safe' name property is funny, because it doesn't gain you anything. Changing a reference type is atomic by nature, as is guaranteed by the .NET framework. So in your example you wrap an atomic operation with a lock statement. What is actually worse is that it degrades performance (because of the lock) and might give you the false sense of thread-safety, especially when using this pattern to all properties in your class. Look at this example:

     

    class Person
    {
    public string FirstName
    {
    get { lock(this) { return _firstName; }
    set { lock(this) { _firstName = value; }
    }

    public string LastName
    {
    get { lock(this) { return _lastName; }
    set { lock(this) { _lastName= value; }
    }
    }

     

    This class might look thread-safe, but there way for users to change the FirstName and LastName in a thread-safe way. Look at the code of two threads:

    Thread 1:

    Person p = GetSharedPersonById(10);
    
    p.FirstName = "Bill";
    p.LastName = "Gates";
    Thread 2:

    Person p = GetSharedPersonById(10);
    
    p.FirstName = "Steve";
    p.LastName = "Jobs";

    When the two threads both have ran, you are the possible states of this shared Person object?

    1. Bill Gates
    2. Steve Jobs
    3. Steve Gates
    4. Bill Jobs

    The only way for both threads to protect them selves from this invalid behavior by making access to both properties atomic like this:

    Person p = GetSharedPersonById(10);
    
    lock (p)
    {
        p.FirstName = "Bill";
        p.LastName = "Gates";
    }

    But of course this totally defeats the purpose of the locks in those properties. The only way to solve this in the Person class is by making the properties readonly and have a single Set method for both properties as follows:

    class Person
    {
        private readonly object locker = new object();
    
        public string FirstName { get; private set; }
    
        public string LastName { get; private set; }
    
        public void SetName(string firstName, string lastName)
        {
            lock (this.locker)
            {
                this.FirstName = firstName;
                this.LastName = lastName;
            }
        }
    }
    Now programmers can safely call the SetName method, with having to worry that Steve Gates or Bill Jobs will fire them :-)


    Visit my blog: http://www.cuttingedge.it/blogs/steven/
    Tuesday, April 13, 2010 7:12 PM