Mutsop
asked on
readonly issue c#
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:
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#?
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;
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#?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
thanks :)
It's weird though when your habits are from vb.net
It's weird though when your habits are from vb.net
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.