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
I would create a class that
That would give you the following code:
public sealed class MyError
{
public static readonly MyError OK = new MyError(0, "OK");
public static readonly MyError Bad = new MyError(1, "Bad Stuff");
private MyError(int id, string message)
{
this.ID = id;
this.Message = message;
}
public int ID { get; private set; }
public string Message { get; private set; }
}
Your properties should not be static because every instance of this class will have their own ID and Message, do you agree?
Your type is not mutable, but Code Analysis doesn't know that.
This warning is a false positive; you should suppress it.
To answer your edited question:
const
can only be applied to primitives.
For custom types, static readonly
is the only option.
As long as the type is properly immutable, it will work perfectly.
The type is not mutable. The Code Analysis gets confused by having public readonly fields.
You can fix the code analysis issue by making your public fields public properties:
public MyError(int id, string message)
{
this.id = id;
this.message = message;
}
private readonly int id;
private readonly string message;
public int Id { get { return id; } }
public string Message { get { return message; } }