visual studio - C# mutability - VS Code Analysis giving me CA2104? Seems... poor. Am I misunderstanding? -


in c#, want make "smart" enums, kind of possible in java, there's more information attached enum value underlying int. happened upon scheme of making class (instead of enum), in following simple example:

public sealed class c {     public static readonly c c1 = new c(0, 1);     public static readonly c c2 = new c(2, 3);      private readonly int x;     private readonly int y;      private c(int x, int y)     {         this.x = x;         this.y = y;     }      public int x     {                 {             return this.x;         }     }      public int y     {                 {             return this.y;         }     } } 

but when run visual studio's "code analyzer" on that, gives me warning c2104, "do not declare read mutable reference types".

i why wouldn't want declare read mutable reference types, but... class not mutable, it?

reading docs warning, seems they're kind of assuming read reference type mutable. example, says if type immutable, feel free suppress warning. , in fact gives me same warning following simpler class:

public sealed class c {     public static readonly c c1 = new c();     public static readonly c c2 = new c();      private c()     {     } } 

so, ok, unless i'm misunderstanding mutability, ca2104 doesn't understand it. , recommendation me suppress warning each line comes up, long i'm sure class immutable. but:

(1) unless turn check off entirely, have suppress every single time ever use immutable read member, might hundreds of times given enumeration?

(2) worse, if that, can later accidentally introduce mutability, else still have false sense of security given fact manually put suppression there saying "i checked , immutable"?

you correct - false positive in scenario. choices suppress individually or turn off warning, , downsides described each option.

other options avoid warning include:

  • don't use static fields. instead, use static property public , private set, , initialize in constructor instead of inline.

  • make these immutable value types, bypass warning, potentially give different behavior in scenarios. may or may not option in case.


Comments

Popular posts from this blog

Perl - how to grep a block of text from a file -

delphi - How to remove all the grips on a coolbar if I have several coolbands? -

javascript - Animating array of divs; only the final element is modified -