c# – assign unique numbers to class instances

Question:

There is a class with messages for the UI. I would like to assign a unique number to each message without writing it manually in the code. These numbers can then be used in tests. So far, it has been done like this:

public class UserMessage
{
    private static int _index = 0;

    private UserMessage(string message)
    {
        this.Code = System.Threading.Interlocked.Increment(ref _index);
        this.Message = message;
    }

    public int Code { get; private set; }
    public string Message { get; private set; }

    public static class Group1
    {
        public static readonly UserMessage msg1 = new UserMessage("msg1");
        // ...            
    }

    public static class Group2
    {
        public static readonly UserMessage msg2 = new UserMessage("msg2");
        // ...            
    }

}

The problem is that the order in which the static constructors are called is undefined, and if the code is executed on different IIS servers, messages may receive different codes. Is it possible to guarantee the same numbering at runtime?

The end goal is to get the same numbering every time the code is executed.

Answer:

If the number is not important to you, then the GUID is ideal for unique tags. Usually in C # I do like this

class MyClass
{

    Guid Id;

    public MyClass()
    {
        Id = Guid.NewGuid();
    }

    public Guid UnicalId
    {
        get
        {
            return Id;
        }
    }
}
Scroll to Top