My Goal: Create a C# class for predefined errors that have both an ID and a Message. Here was what I tried:
public class MyError
{
public static readonly MyError OK = new MyError(0, "OK");
public static readonly MyError Bad = new MyError(1, "Bad Stuff");
public MyError(int id, string message)
{
this.Id = id;
this.Message = message;
}
public readonly int Id;
public readonly string Message;
}
This compiles just fine and I am sure it would work just fine in practice. But I always like to follow Code Analysis guidelines. In the above case, CA2104 is violated "Do not declare read only mutable reference types"
I have tried a number of things other than the above, including trying const instead of readonly (won't even compile), { get; private set; } for member access, struct instead of class, etc.
Which is the mutable type? Id or Message?
I'm open to any suggestions that accomplish what I want: Pre-defined constants for non-trivial data types.
Of course, I can always just ignore the warning but I have found that there is usually a reason for them.
* CLARIFICATION * My question is really less about this specific MyError class and more about a more fundamental problem of defining constants for stuff other than basic data types.
Suppose I want to define three constants that are doubles. C# lets me do this like so:
public const double HighValue = 11.0;
public const double LowValue = 0.1;
public const double MidValue = 5.5;
C# creates a small handful of useful constants for double pre-defined for us: NaN, MinValue, MaxValue, NegativeInfinity, PositiveInfinity.
So now, what if I want to pre-define some interesting constants for three-dimensional vectors (X,Y,Z) in space? I can define constants for doubles, integers, strings, etc. but how do I define a constant for something less trivial? The Origin is an interesting constant I want to give a name to:
public class Vector3D
{
/// The problem is that this does not work
public const Vector3D Origin = { 0.0, 0.0, 0.0 };
public double X;
public double Y;
public double Z;
}
I'm not going to need thousands of constants. Just a few like our friend double has with NaN, etc. The class doesn't need to be especially protected or sealed either. Anybody is free to create Vector3D objects and derive from it in any way they want. I just want to have a special constant named Origin that has value (0.0, 0.0, 0.0)