Tuesday, August 5, 2008

Generics Issues

I've never really used Generics before so I'm still struggling with it.
What I think I want to do, is have a method that returns List;. I can return the list ok, and I can use Activator to create new T objects. The only problem is that my test requires some boxing, which is what I want to avoid. I'm wondering if the boxing will disappear in a real world example.

test code



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

namespace GenericsTest
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Test 1");
Factory fact = new Factory();
List<obint>; test1 = fact.GetList<obint>();
foreach (ObInt item in test1)
{
Console.WriteLine(item.Data);
}

Console.WriteLine("\nTest Two");
List<int> test2 = new List<int>();
test2.Add(1);
test2.Add(2);
test2.Add(3);
foreach (int item in test2)
{
Console.WriteLine(item);
}

Console.WriteLine("Done, hit anykey");
Console.Read();

}
}

//The Goal is to see if I can return a Generic list
public class Factory
{
public List<t> GetList<t>() where T : IObject
{
List<t> list = new List<t>();

T tmp = Activator.CreateInstance<t>();
tmp.Add(5);

list.Add(tmp);

return list;
}
}

public interface IObject
{
void Add(object item);
}

public class ObInt : IObject
{
protected int _data;
public int Data
{
get { return _data; }
set { _data = value; }
}

public ObInt(int data)
{
_data = data;
}
public ObInt() { }

public void Add(object item)
{
_data = (int)item;
}

}

public class ObString: IObject
{
protected string _data;
public string Data
{
get { return _data; }
set { _data = value; }
}

public ObString(string data)
{
_data = data;
}
public ObString() { }

public void Add(object item)
{
_data = item.ToString();
}
}
}

No comments: