List of Funny Objects

I have played with generics and I have one question.

Take this simple sample:

using System;
using System.Collections.Generic;
using System.Text;

namespace FunnyTests
{
    public class Funny<T>
    {
        private T _value;

        public T Value
        {
            get { return _value;}
            set { _value = value;}
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Funny<int> someInt = new Funny<int>();
            someInt.Value = 10;

            Funny<string> someString = new Funny<string>();
            someString.Value = "Test";

            // *************************************************
            // List<Funny> myFunnyList = new List<Funny>();
            // *************************************************

            List<Funny<int>> myFunnyIntList = new List<Funny<int>>();
            List<Funny<string>> myFunnyStringList = new List<Funny<string>>();
            
        }
    }
}

Well, I wish one List of Funny objects (independent of T is string, integer, etc.), but with the code above I can't. The commented code is what I wish, and the another 2 is what I can do.

Resuming: I can have only lists of (by example) Funny<int> objects or Funny<string> objects, but not "Funny" objects...

Someone have sugestions
Thanks for all



Answer this question

List of Funny Objects

  • Rui Silva18093

    If you want a list of Funny objects, use an interface like so:

    interface IFunny {
        //funny stuff
    }

    public class Funny<T> : IFunny
    {
        //internals
    }

    Now you can do:

    List<IFunny> myList = new List<IFunny>();

    and put your Funny objects in there.



  • Michael Tsai

    Well the problem is that you don't have a Funny class.  You have a Funny<T> class.  At the point you create the List object you have to provide a type parameter and if that type parameter is itself generic then it must be a "closed constructed" type.  That is, you must specify the type so that the JIT'er can create a List of the specified type.  What you are doing is this:

    List<Funny<T>> myFunnyList = new List<Funny<T>>();

    The "Funny<T>" type parameter is an "open constructed" type meaning that it hasn't been fully specified yet.  Hence the JIT'er can't JIT the Funny<T> type and therefore there isn't a type you can use yet for the List instantiation. 

    If you want to truly allow different flavors of objects (even Funny objects), perhaps you should use:

    List<object> myFunnyList = new List<object>();


  • List of Funny Objects