show-notice
hide-notice

Friday 5 July 2013

Create an index for a class





Questions



I have a class called undergrad which keeps track of students first and last names. I would like each object to have an index. In my program class, I create a List<> of undergrads. How would I set it so each object in the list has a unique identifying number, and what would it look like in the program class?



public class Undergrad
    {
        String fName, lName;

        public Undergrad()
        {
        }

        public Undergrad(string firstName, string lastName)
        {
            this.fName = firstName;
            this.lName = lastName;
        }
    }



Answers

You would need to add a property to the class to store that index for starters. This could either be an integer or a UniqueIdentifer.
If you go with an integer, you'll need somewhere else (such as a database) to store all the indices so that you're application knows where to get the next value at.
With a UniqueIdentifer (System.Guid) you won't get duplicate collisions so you could just create that inline.

OPTION 1
public class Undergrad
    {
        String fName, lName;
        public Guid UniqueId { get; set; }

        public Undergrad()
        {
            UniqueId = System.Guid.NewGuid();
        }

        public Undergrad(string firstName, string lastName)
        {
            UniqueId = System.Guid.NewGuid();
            this.fName = firstName;
            this.lName = lastName;
        }
    }



Option 2

public class Undergrad
    {
        String fName, lName;
        public int UniqueId { get; set; }

        public Undergrad()
     {
          UniqueId = //LoadFromDatabase();
     }

        public Undergrad(string firstName, string lastName)
        {
            UniqueId = //LoadFromDatabase();
            this.fName = firstName;
            this.lName = lastName;
        }
    }
Where are you currently storing your undergrad information ? if it's in a database already, I'd expect you to have an id field on the object already.
Last thing, when you put these into a List<T>, the list will have it's own index (for position within the list) which is a separate concept.

SHARE THIS POST   

0 comments :

Post a Comment

Design by Gohilinfotech | www.gohilinfotech.blogspot.com