C # volatility - does VS Code Analysis give me CA2104? Seems ... poor. I do not understand?

In C #, I want to make smart enumerations, like what is possible in Java, where there is more information tied to the enumeration value than just the base int. I came up with a class creation scheme (instead of listing), as in the 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 { get { return this.x; } } public int Y { get { return this.y; } } } 

But when I start Visual Studio "Code Analyzer", it gives me warning C2104 "Do not declare only mutable types of read links."

I understand why you wouldn't want to declare read only mutable link types at all, but ... my class is not mutable, right?

Reading documents for warning, it looks like they just assume that any type of read-only link is mutable. For example, it says that if the type is truly immutable, then feel free to suppress this warning. And actually it gives me the same warning for the following even simpler class:

 public sealed class C { public static readonly C C1 = new C(); public static readonly C C2 = new C(); private C() { } } 

So, well, if I seriously do not understand volatility, CA2104 does not understand this. And his recommendation is that I suppress the warning for every line where it appears, if I'm sure the class is really immutable. But:

(1) So, if I don’t completely disable this check, should I suppress it every time I ever use a read-only immutable member that I could do over the centuries for any given listing?

(2) But worse, even if I do, then someone later may accidentally introduce variability, but someone else will have a false sense of security given by someone manually putting the suppression in there, saying: β€œI checked and is it immutable "?

+7
source share
1 answer

You are right - this is a false positive in this scenario. Your only choice is to suppress separately or turn off the warning, and the bottom ones are exactly the same as you described for each option.

Other options to prevent this warning include:

  • Do not use static fields. Instead, you can use the static property with the public get and private set and initialize the constructor instead of the built-in one.

  • Make these immutable value types that will bypass the warning, but could potentially lead to behavior in some scenarios. This may or may not be an option in your case.

+5
source

All Articles