We help IT Professionals succeed at work.

readonly issue c#

Mutsop
Mutsop asked
on
Hi,

So I have a class Player which contains a few properties that shouldn't be modified after creating a player object... So for this purpose I make it readonly.

One thing though: There are readonly properties that should be modified through Methods.

So before (in vb.net) a made  private property and a public readonly property which returned the private one.

For example:
public readonly Int32 Health
        {
            get { return _Health; }
        }
 public void modifyHealth(Int32 health)
        {
            _Health += health;
            if (_Health < 0) { _Health = 0; }
            else if (_Health > 100) { _Health = 100; }
            //Might be changed later on.
        }

        //Health set in Hero class/Card class.
        private Int32 _Health;

Open in new window


When my solution is cleaned I don't get any errors but once I build it I get following errors:
"The modifier 'readonly' is not valid for this item".

How is this done in c#?


Comment
Watch Question

Freelance programmer / Consultant
Commented:
remove the 'readonly' keyword
AndyAinscowFreelance programmer / Consultant

Commented:
It really is that simple.
The readonly keyword only applies when declaring a variable (in C#) and means you could only set the value when initialising the variable.  The absence of a public 'set' in the accesor method makes it readonly.

Author

Commented:
thanks :)

It's weird though when your habits are from vb.net