C
C#3y 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
Angius3y ago
private means available only in that class protected would be available in that class and its descendants
LukeJ
LukeJOP3y ago
Everything was public though.
Angius
Angius3y 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 User3y ago
Message Not Public
Sign In & Join Server To View
TheRanger
TheRanger3y 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
nathanAjacobs3y 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
Accord3y ago
✅ This post has been marked as answered!
Want results from more Discord servers?
Add your server