C # generic questions

advertisements

I'm trying to complete a practice question from a book on generics but the question doesn't make sense to me. Here it goes.

Create two classes with identical functionality. Use generics for the first class, and cast the second class to Object types. Create a for loop that uses class and the Object based class to determine which performs better.

I'm not sure what it means by casting to Object types. Here is my code so far

   //Generic
    class Person<T> {

        T var1;

        public Person(T yer) {
            var1 = yer;
        }

        public T Value { get { return var1; } }
    }

    //Normal class
    class Human {

        int var1;

        public Human(int yer) {
            var1 = yer;
        }

        public int Value { get { return var1; } }
    }

My main program running the loops

for (int i = 0; i < 1000000; i++) {
                Person<int> me = new Person<int>(1);
                int hey = me.Value;
            }

            for (int i = 0; i < 1000000; i++) {
                Human per = new Human(1);
                object her = (object)per.Value;
            }

I don't know if Im doing this right. Help please :-)


I think that the question is asking you to create a collection class, and insert instances of your class into that.

E.g.,

Generics version:

List<Human> myList = new List<Human>();
Human h = new Human();
myList.Add(h);

Object version:

ArrayList myObjectList = new ArrayList();
Human h = new Human();
myObjectList.Add((object)h));

I haven't checked whether that compiles, and have to run now.