This post has been de-listed
It is no longer included in search results and normal feeds (front page, hot posts, subreddit posts, etc). It remains visible only via the author's post history.
super class, where I want to be able to freely change Viable:
namespace Life
{
class Egg
{
public double Size { get; private set; }
public string Type { get; private set; }
public virtual bool Viable { get; set; } = true;
public Egg(string type, double size)
{
this.Type = type;
this.Size = size;
}
}
}
sub class, where I want Viable to always be false:
namespace Life
{
internal class BrokenEgg : Egg
{
public override bool Viable { get; set; } = false;
public BrokenEgg(string type) : base("broken " type,0)
{
}
}
}
I cannot change Viable to a private setter in the sub class, but I want to (a broken egg would never be viable). I suppose I could use a private field for Egg and have the setter use that.
internal class BrokenEgg : Egg
{
private bool _viable = false;
public override bool Viable {
get { return _viable; }
set { }
}
public BrokenEgg(string type) : base("broken " type,0)
{
}
}
Alternatively, I could have the getter for BrokenEgg simply return false.
public override bool Viable {
get { return false; }
set { }
}
I'm just not really sure what's the best idea here. Both of the solutions I have would let you do something like BrokenEgg.Viable = true; and everything would compile and you'd think the code worked fine.
the third option, and my favorite, is to put in an error myself:
public override bool Viable {
get { return false; }
set { throw new InvalidOperationException("you cannot set a BrokenEgg's Viabilility"); }
}
I actually think I really like this idea because I could explain the reasoning and it makes me explain the reasoning, too. It doesn't just look like a technical error.
Subreddit
Post Details
- Posted
- 2 years ago
- Reddit URL
- View post on reddit.com
- External URL
- reddit.com/r/csharp/comm...