C
C#2y ago
LukeJ

Cannot set readonly field in inherited constructor [Answered]

Title says it all really, I'm not really sure why given this is clearly a constructor.
public class StandardCard : Card {
public StandardCard(Suite suite, Rank rank) {
if (!StandardRanks.ranks.Contains(rank))
throw new Exception();

this.suite = suite;
this.rank = rank;
}
}
public class StandardCard : Card {
public StandardCard(Suite suite, Rank rank) {
if (!StandardRanks.ranks.Contains(rank))
throw new Exception();

this.suite = suite;
this.rank = rank;
}
}
7 Replies
Angius
Angius2y ago
private means available only in that class protected would be available in that class and its descendants
LukeJ
LukeJ2y ago
Everything was public though.
Angius
Angius2y ago
Ah, huh, could be because of the readonly then..? Easiest solution would be to just make it a get-only property instead
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
TheRanger
TheRanger2y ago
u can call the base constructor with : base() if the base constructor sets a value to that readonly field instead of setting the field with the child constructor
nathanAjacobs
nathanAjacobs2y ago
Couldn't you also just use init on the property like this?
public class BaseClass
{
public int Prop { init; get; }

public BaseClass()
{
Prop = 1;
}
}

public class ChildClass : BaseClass
{
public ChildClass()
{
Prop = 1;
}
}
public class BaseClass
{
public int Prop { init; get; }

public BaseClass()
{
Prop = 1;
}
}

public class ChildClass : BaseClass
{
public ChildClass()
{
Prop = 1;
}
}
Accord
Accord2y ago
✅ This post has been marked as answered!