having code like this:
public static readonly bool MaximumRecipientsReached;
private static readonly IList<EmailAddress> Contacts;
static AdditionalRecipient()
{
Contacts = AnotherClass.Contacts; //works
}
public AdditionalRecipient()
{
MaximumRecipientsReached = true; //works not
}
Why can I change a private static readonly field but not a public one?
PS: of course I am using properties.
In your first example, you are changing it in the static constructor, which is allowed, if you changed it in any other static method/property, it would be a compiler error.
In your second example, you are attempting to change a
static readonlymember in a non-static constructor, which isn’t allowed.You can only change
static readonlymembers in thestaticconstructor. Think of it this way, thestaticconstructor runs once, and after that for each instance the instance constructor is invoked. The property wouldn’t be veryreadonlyif every instance could change it.You can, of course, change non-
staticreadonlyinstance members in the constructor:Also, I’m confused by your “PS: of course I am using properties”. Properties cannot be declared
readonly, if you wanted these to be properties and to bereadonly-ish, you’d need to make themprivate set– unless of course you are using a backing field. The main reason I bring this up is because using a property with a private set would allow you to do what your code is trying to do, as the class itself can change the property (static or instance) in any method or constructor, but code outside of the class can not.