I have an abstract class, Card, whose implementations inherit several public readonly values like Name and Text. While creating an implementation of a card, in the constructor i assign these variables different values but VS is giving me this compile error:
"A readonly field cannot be assigned to (except in a constructor or variable intializer)"
Does this property not carry through inheritence? If not, how should I structure this? Example:
abstract class Card
{
public readonly int Id, Attack, Defense, Speed;
}
class ExampleCard: Card
{
public ExampleCard()
{
//Set card metrics
Id = 0;
Attack = 10;
Defense = 5;
Speed = 1;
}
}
There were some format issues with the copy/pasting but this is more or less what i've got. I do not want these fields to be const and i really do not want to have to redifine them (with the new keyword) every time i create a new implementation of the Card
class.
A readonly field can only be assigned as part of its declaration or in an instance or static constructor for the class. So, your subclass needs to call a constructor of the base class which does the initialisation. Something like
abstract class Card
{
public readonly int Id, Attack; //etc
protected Card(int id, int attack)
{
Id = id;
Attack = attack;
}
}
class ExampleCard : Card
{
public ExampleCard() : base(0, 10)
{ }
}
jokul
0 Points
7 Posts
Unable to intialize inherited readonly variables in constructor?
Dec 16, 2012 08:12 AM|LINK
I have an abstract class, Card, whose implementations inherit several public readonly values like Name and Text. While creating an implementation of a card, in the constructor i assign these variables different values but VS is giving me this compile error:
"A readonly field cannot be assigned to (except in a constructor or variable intializer)"
Does this property not carry through inheritence? If not, how should I structure this? Example:
abstract class Card { public readonly int Id, Attack, Defense, Speed; } class ExampleCard: Card { public ExampleCard() { //Set card metrics Id = 0; Attack = 10; Defense = 5; Speed = 1; } }There were some format issues with the copy/pasting but this is more or less what i've got. I do not want these fields to be const and i really do not want to have to redifine them (with the new keyword) every time i create a new implementation of the Card class.
Paul Linton
Star
13431 Points
2535 Posts
Re: Unable to intialize inherited readonly variables in constructor?
Dec 16, 2012 08:43 PM|LINK
A readonly field can only be assigned as part of its declaration or in an instance or static constructor for the class. So, your subclass needs to call a constructor of the base class which does the initialisation. Something like
abstract class Card { public readonly int Id, Attack; //etc protected Card(int id, int attack) { Id = id; Attack = attack; } } class ExampleCard : Card { public ExampleCard() : base(0, 10) { } }