I have a class like:
class SomeTests {
private Guid[] someGuids = new Guid[] { ... }
public void ThoseGuidsShouldAlwaysBeThere() {
foreach (Guid g in someGuids) { // error appears here
// ...
}
}
}
Semantically, I want someGuids to be const, since they shouldn’t be updated, ever, except before recompiling the code. But adding the const keyword generates error CS0168: null is not valid in this context.
Reading the MSDN page for that error, it seems to me that the compiler thinks I’m doing this:
foreach (Guid g in null) {
I don’t understand how adding const causes this problem here, and how to solve my semantic problem (list is read-only, not writable) — keeping it as an array instead of a List is “almost” good enough.
Trying to make
Guid[]a constant should give you an error of “A const field of a reference type other than string can only be initialized with null.”Make it
readonlyinstead:When it’s
readonlyyou can also assign the value in the constructor:As Jeffery mentioned in the comments, this solution prevents
someGuidsfrom being reassigned, but the items can still be modified. Jeffery addresses this issue in his answer.