How to create a method that will create a unique number that won't be repeated?

I am trying to link 2 different classes together. Relationship is a one to many relationship. So I'm trying to make a program which will let me make every object unique. So I decided to add Unique IDs to each object. How can I make a method that will give me a unique number that won't be repeated. I'm using C# .net5.0.

EDIT: a method that just gives a number that hasn't been used before is ok too. For example, 1, and then it will check if 1 has been used before if not than it will use one and if yes than it will use 2

Upvotes: 0

Views: 1223

Answers (1)

Neil T
Neil T

Reputation: 3285

You could use a static counter, something like this:

class Thing {

    static int IdCount;

    private int id;

    public Thing() {
        IdCount++;
        this.id = IdCount;
    }
    
    ...

}

The counter will be zero initially (the default integer value) and will increment on each instantiation of the class and assign the new value to the ID field of the object.

Be aware that this is not thread-safe and may not be appropriate for your needs.

EDIT (following question edit and comment):

You could use a function to generate the ID number but you should still consider thread-safety. A simple lock might be enough for your needs, something like this:

class Thing {

    static int IdCount;
    static readonly object objectLock = new object();
    
    private int id;

    public Thing() {
        this.id = GetIdNumber();
    }
    
    private static GetIdNumber() {
        lock (objectLock) {
            IdCount++;
            return IdCount;        
        }
    }
}

The lock will prevent a second, near-simultaneous instantiation from incrementing the counter before the first instantiation has had chance to return the number. For anything more complex you could look at (e.g.) the Interlocked class.

It should be obvious that the above are runtime-only solutions; values will not persist outside the lifetime of the application.

Upvotes: 1

Related Questions