Friday 15 May 2015

c# - Setting read-only fields in a chained constructor -



c# - Setting read-only fields in a chained constructor -

i have class 2 read-only fields beingness set in constructor. have derived class set these different values in constructor; however, trying results in cs1091 (a readonly field cannot assigned (except in constructor or variable initializer) error.

i don't see why - am assigning fields in constructor. not 1 of class they're defined.

is there subtle syntax issue i'm missing, or not possible?

(there's ways around if isn't possible - protected virtual property without setter, , private readonly backing fields; syntactically it's not going clean, however, wanted avoid them if can.)

public class baseclass { protected readonly ushort offsetroutine; protected readonly ushort offsetstring; public baseclass() { this.offsetroutine = this.getword(addresses.header.offsetroutine); this.offsetstring = this.getword(addresses.header.offsetstring); } protected ushort getword(byte address) { // chosen fair dice roll on d100. homecoming 42; } } public class derivedclass : baseclass { public derivedclass() : base() { this.offsetroutine = 0; this.offsetstring = 0; } }

the other answers not providing key detail - setting readonly field allowed in declaration or constructor of same class. 1 of differences between readonly , const. const modifier not allow set field in constructor - in declaration. setting readonly in derived class not allowed since field not in same class. assume don't need workarounds seemed know how go if necessary, , there other answers discussing that. msdn (http://msdn.microsoft.com/en-us/library/acdd6hb7.aspx):

when field declaration includes readonly modifier, assignments fields introduced declaration can occur part of declaration or in constructor in same class.

just few examples:

public class { protected const string conststring = "test"; //allowed protected readonly string readonlystring = "test"; //allowed public a(){ conststring = "test"; //not allowed readonlystring = "test"; //allowed } } public class b: { public b(){ conststring = "test"; //not allowed readonlystring = "test"; //not allowed } }

c#

No comments:

Post a Comment