Question

Generics rookie struggling to access a list inside a class which is contained in a list. Basically I am trying to list the occupations of people that the user entered (I am sure there is an easier way of doing this, but this code was made to practise generics).

Class Code

namespace GenericPersonClass
{
class GenericPerson<T>
{
    static public List<T> Occupations = new List<T>();
    string name, famName;
    int age;

    public GenericPerson(string nameS,string famNameS,int ageI, T Note)
    {
        name = nameS;
        famName = famNameS;
        age = ageI;
        Occupations.Add(Note);
    }

    public override string  ToString()
        {

            return "The name is " + name + " " + famName + " and they are " + age;
        }
  }
}

Main Code

namespace GenericPersonClass
{
class Program
{
    static void Main(string[] args)
    {
        string token=null;
        string nameS, lastNameS,occS;
        int age;
        List<GenericPerson<string>> Workers = new List<GenericPerson<string>>();

        while (token != "no" || token != "No")
        {
            Console.WriteLine("Please enter the first name of the person to input");
            nameS = Console.ReadLine();
            Console.WriteLine("Please enter the last name of the person " + nameS);
            lastNameS = Console.ReadLine();
            Console.WriteLine("How old is " + nameS + " " + lastNameS);
            age = int.Parse(Console.ReadLine());
            Console.WriteLine("What is the occupation of " + nameS + " " + lastNameS);
            occS = Console.ReadLine();
            Console.WriteLine("Enter more data?...Yes/No");
            Workers.Add(new GenericPerson<string>(nameS, lastNameS, age, occS));
            token = Console.ReadLine();
        }

        Console.WriteLine("You provide the following employment...\n");
        for (int i = 0; i < Workers.Count; ++i)
        {
            Console.WriteLine("{0} \n", Workers[0].Occupations[i]); 
//This line above is shown as wrong by VS2010, and intellisense does not see Occupations...
        }

    }
}
}

Thanks for any help, Leo

Was it helpful?

Solution

So, you're trying to access a static List from an instance variable. That's the problem there. You can access this directly by using the class not the instance.

Something like:

GenericPerson<string>.Occupations[i]

It doesn't have anything to do with the List - it's all about the static part.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top