Friday, March 19, 2010

Is read-only auto-imlemented property possible?

Programmer Question

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?



Find the answer here

No comments:

Post a Comment

LinkWithin

Related Posts with Thumbnails