Readonly property vs. readonly member variable in C#

I have a class ExProperty something like below:

class ExProperty
{
    private int m_asimplevar;
    private readonly int _s=2;

    public ExProperty(int iTemp)
    {
        m_asimplevar = iTemp;  
    }

    public void Asimplemethod()
    {
        System.Console.WriteLine(m_asimplevar);
    }

    public int Property
    {
        get {return m_asimplevar ;}
        //since there is no set, this property is just made readonly.
    }
}

class Program
{
    static void Main(string[] args)
    {
        var ap = new ExProperty(2);
        Console.WriteLine(ap.Property);
    }
}
  1. What is the sole purpose of making/using a property readonly or write only? I see, through the following program that readonly achieves the same purpose!

  2. When I make the property read-only, I think it should not be writable. When I use

    public void Asimplemethod()
    {
        _s=3; //Compiler reports as "Read only field cannot be used as assignment"
        System.Console.WriteLine(m_asimplevar);
    }
    

    Yes, this is ok.

    But, If i use

    public ExProperty(int iTemp)
    {
        _s = 3 ; //compiler reports no error. May be read-only does not apply to constructors functions ?
    }
    

    Why does the compiler report no error in this case ?

  3. Is declaring _s=3 ok? Or should I declare _s and assign its value using a constructor?

Upvotes: 3

Views: 2606

Answers (2)

Jeppe Stig Nielsen
Jeppe Stig Nielsen

Reputation: 61950

Yes, the readonly keyword means that the field can be written to only in a field initializer and in constructors.

If you want, you can combine readonly with the property approach. The private backing field for the property can be declared readonly while the property itself has only a getter. Then the backing field can be assigned to only in constructors (and in its possible field initializer).

Another thing you could consider is making a public readonly field. Since the field itself is read-only, you actually don't achieve much from the getter if all it does is returning the field value.

Upvotes: 5

Euphoric
Euphoric

Reputation: 12849

Key point of properties is to provide interface for outside of the class. By not defining Set or by making it private, you make it "read-only" for outside of the class, but it can still be changed from inside of the class methods.

By making field readonly, you are saying it should never change, no matter from where this change comes.

Upvotes: 3

Related Questions