Is read-only auto-imlemented property possible?

Posted by abatishchev on Stack Overflow See other posts from Stack Overflow or by abatishchev
Published on 2010-03-19T20:50:44Z Indexed on 2010/03/19 21:01 UTC
Read the original article Hit count: 132

Filed under:
|
|
|
|

Hello. I found a topic on MSDN that talks that yes, this is possible.

I did a test that seems to break this statement:

using System;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            Foo f = new Foo("1");
            Console.WriteLine(f.Bar); // prints 1
            f.Test("2");
            Console.WriteLine(f.Bar);// successfully prints 2
        }
    }

    class Foo
    {
        public Foo(string b)
        {
            this.Bar = b;
        }

        public string Bar { get; private set; }

        public void Test(string b)
        {
            // this would be impossible for readonly field!
            // next error would be occur: CS0191 or CS0191
            // A readonly field cannot be assigned to (except in a constructor or a variable initializer)
            this.Bar = b; 
        }
    }
}

Where am I wrong?

© Stack Overflow or respective owner

Related posts about .NET

Related posts about c#