简体   繁体   中英

c# how to increment id for each instance of class automatically

A user inserts KID NAME, the code instantiate an object and add it to list of objects. How to give each object a unique number automatically starting at 1, such that first KID(object) gets number 1, second KID gets number 2 etc. I tried something like this but the result is "stackoverflow". How would the class should be?

class Kid
    {
        public string KidName{ get; set; }
        private static int Number { get; set; }
        public int KidNumber { get; set; }
        
        public Kid (string name)
        {
            this.KidName = name;
            Number++;
            this.KidNumber = Number;
        }
    }

Your code works successfully on my device. Maybe you have an 'stackoverflow' for other reasons?

If you need only to identify Kid class, the alternative way is to use Guid:

class Kid
{
    public string KidName { get; set; }
    public Guid KidNumber { get; set; }

    public Kid(string name)
    {
        this.KidName = name;
        this.KidNumber = Guid.NewGuid();
    }
}

Nothing in your example can induce a StackOverflowException . Stackoverflows occur when you repeatedly call the same method recursively either directly or indirectly (by way of an intermediate) or when you have an instance-level field of the same type as the instance itself (a special case of the former). You don't exhibit either case in your example so it must be due to something else external to the code you've shown. The most your code could potentially exhibit is an OverflowException if you were in a checked context .

That said, your approach is OK at first glance with the obvious pitfall that it is not thread-safe. Two instance could in theory end up with the same KidNumber . You can fix that by making use of the Interlocked class:

using System.Threading;

class Kid
{
    private static int _counter;
    public string KidName { get; set; }
    public int KidNumber { get; set; }
    
    public Kid(string name)
    {
        this.KidName = name;
        this.KidNumber = Interlocked.Increment(ref _counter);
    }
}

Like ++ in an unchecked context, this handles the case of overflow; once you hit int.MaxValue , if will automatically wrap to int.MinValue . If you don't want negative IDs you'll have to handle that seperately.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM