Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can ValueTuple not be const?

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;
}
like image 300
Alex Butenko Avatar asked Apr 21 '19 20:04

Alex Butenko


Video Answer


1 Answers

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.

like image 173
Renat Avatar answered Oct 12 '22 04:10

Renat