Creating a const array means that "using null in this context is unacceptable"

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 be const , since they should not be updated, unless the code is recompiled. But adding the const keyword generates error CS0168 : null is not valid in this context.

Reading the MSDN page for this error, it seems to me that the compiler thinks I am 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 (the list is read-only, not writable) - saving it as an array instead of an β€œalmost” list is good enough.

+4
source share
2 answers

Trying to make a Guid[] constant should give you the error "A constant field of a reference type, other than a string, can only be initialized to zero."

Do readonly instead:

 private readonly Guid[] someGuids = new Guid[] { Guid.NewGuid() }; 

When it is readonly , you can also assign a value in the constructor:

 public SomeTests() { someGuids = new[] { Guid.NewGuid(), Guid.NewGuid() }; } 

As Jeffrey noted in the comments, this solution prevents the reassignment of someGuids , but the elements can still be changed. Jeffrey solves this problem in his answer.

+2
source

The readonly keyword in this use is a bit misleading. Look at this as preventing re-instantiation of a collection, not a change.

Example:

  private readonly Guid[] someGuids = new Guid[] { Guid.NewGuid() }; //This will not compile because it is read-only. someGuids = new Guid[] { Guid.NewGuid() }; //This still compiles, and the first member will be changed someGuids[0] = Guid.NewGuid(); 

I recommend that you use System.Collections.ObjectModel.ReadOnlyCollection<T> in combination with the readonly keyword.

Example:

  public readonly ReadOnlyCollection<Guid> someGuids = new ReadOnlyCollection<Guid>(new Guid[] { Guid.NewGuid(), Guid.NewGuid() }); 

The collection can no longer be re-created, and its members cannot be changed.

+3
source

All Articles