I tried the following example:
public class TestBase
{
public virtual string ReadOnly { get; }
public TestBase()
{
ReadOnly = "from base";
}
}
class Test : TestBase
{
public override string ReadOnly { get; }
public Test()
{
// nothing here
}
}
When I create an instance of Test, I see that ReadOnly stays null. But why? I really do not get the hang of it, could somebody please explain to me why this happens? At least I would expect an error, that a read-only property cannot be set outside of the owning class.
virtual
keyword here, sorry. – SingularReadOnly
may be a confusing variable name to use in this instance. As I understand it, you are overriding a base classes property which can only be set within the constructor ({get;}
). It isn't set, and is thereforenull
. – FabrikoidConsole.WriteLine(ReadOnly);
in the base constructor, after assigning to the property. – Handspringpublic override string ReadOnly => base.ReadOnly;
– Aluminate