Why can ValueTuple not be const?

Asked by At

ValueTuple types, declared as fields, can be mutable:

class Foo {
  (int, int) bar = (0, 1);
}

or readonly:

class Foo {
  readonly (int, int) bar = (0, 1);
}

and this (im)mutability applies to each member. I would expect it to be stretched to const declarations as well:

class Foo {
  const (int, int) bar = (0, 1);
}

But this statement does not compile. Is there a certain case where it is an undesirable feature, or is it just something not implemented?

EDIT OK, I understand now. My question was based on the assumption that the C# compiler treats ValueTuples differently than other types, regarding the keyword readonly. So, if it is already an exception, why not make another exception for consts. But, in fact, this logic seems to be applied to all structs. So this will not work:

class Foo {
  readonly ExampleStruct field;
  void Method() {
    field.structField = 2;
  }
}
struct ExampleStruct {
  public int structField;
}

1 Answers

4
Renat On Best Solutions

There is a limited set of types, which could be used as const in c# (more detailed here).

Value tuple is simply not among them.