Click here to Skip to main content
14,640,725 members

Writing to readonly variables

Member 13566383 asked:

Open original thread
In the following code I defined a class Polynomial which contains an array marked readonly.
I defined a read property. A write property can not be defined because of compiler error CS0191. That is OK.
But if I try to write using (the non existing) write property for example p.Coeff[2] = 19 it works! How can that be?
I made some further tests:
A: I defined an indexer. The compiler does not prevent me from defining a write property. It can be used to modify the readonly member data.
B: I used my Polynomial object p as a parameter to the method UsePolynomial with the key word in. I understand the argument is passed by reference in order to avoid unnecessary copy operations if the parameter object will not be modified. The compiler should not allow any operations which modify the object. But there is no problem to modify p. Any changes made in the method called are available after returning from the call.
Here is my programm:
namespace PolyTest
{
    class Program
    {
        public class Polynomial
        {
            readonly private double[] coeff;
            public double[] Coeff { get => coeff;} // Does not allow set property because coeff is readonly (CS0191)
            public double this[int i] { get => coeff[i]; set => coeff[i] = value; }
            public Polynomial(double c0, double c1, double c2)
            {
                coeff = new double[] { c0, c1, c2 };
            }
        }
        static void Main(string[] args)
        {
            Polynomial p = new Polynomial(1, 2, 3);
            UsePolynomial(p);
            double val = p[2];          // val = 17 (or 18 if the last line in UsePolynomial is uncommented)
        }

        static void UsePolynomial(in Polynomial p)
        {
            double val1 = p.Coeff[2];   // val1 = 3  OK
            double val2 = p[2];         // Val2 = 3  OK
            p.Coeff[2] = 17;            // Why is that possible?
            //p[2] = 18;                  // Why is that possible?
        }
    }
}


What I have tried:

What I have tried you can read in the question.
Tags: C#

Preview



When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
  4. Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the The Code Project Open License (CPOL).




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100