Good day. Generics usually used like this:
class MyList<T>
{
public T data;
public MyList<T> nextElement;
}
Why not instead use follow:
class MyList
{
public object data;
public MyList nextElement;
}
Or even:
class MyStructure<T> where T : SomeCommonClass
{
public T data;
public MyStructure<T> nextElement;
public MyStructure<T> prevElement;
}
and instead:
class MyStructure
{
public SomeCommonClass data;
public MyStructure nextElement;
public MyStructure prevElement;
}
Update:
Well, I am afraid that you are not completely understood me correctly, and even downgraded my question. Example without generics, that work correctly:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
MyNode nodeButton = new MyNode("nodeButton", new Button());
MyNode nodeTextBox = new MyNode("nodeTextBox", new TextBox());
MyNode nodeCheckBox = new MyNode("nodeCheckBox", new CheckBox());
MyList myList = new MyList() { nodeButton, nodeTextBox, nodeCheckBox };
for (int i = 0; i < myList.Count;i++)
{
this.Controls.Add(myList[i].Data);
myList[i].Data.Left = 100 * i;
}
}
}
public class MyNode
{
public MyNode(string name, Control data)
{
Data = data;
Name = name;
}
public string Name { get; private set; }
public Control Data { get; private set; }
}
public class MyList : Collection<MyNode>
{
protected override void InsertItem(int index, MyNode item)
{
base.InsertItem(index, item);
item.Data.MouseClick += new MouseEventHandler((sender, e) => { MessageBox.Show(item.Name); });
}
}
And same example with generics, that generates an error at compile time:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
MyNode<Button> nodeButton = new MyNode<Button>("nodeButton", new Button());
MyNode<TextBox> nodeTextBox = new MyNode<TextBox>("nodeTextBox", new TextBox());
MyNode<CheckBox> nodeCheckBox = new MyNode<CheckBox>("nodeCheckBox", new CheckBox());
MyList myList = new MyList() { (MyNode<Control>)nodeButton, (MyNode<Control>)nodeTextBox, (MyNode<Control>)nodeCheckBox };
for (int i = 0; i < myList.Count;i++)
{
this.Controls.Add(myList[i].Data);
myList[i].Data.Left = 100 * i;
}
}
}
public class MyNode<T> where T : Control
{
public MyNode(string name, T data)
{
Data = data;
Name = name;
}
public string Name { get; private set; }
public T Data { get; private set; }
}
public class MyList : Collection<MyNode<Control>>
{
protected override void InsertItem(int index, MyNode<Control> item)
{
base.InsertItem(index, item);
item.Data.MouseClick += new MouseEventHandler((sender, e) => { MessageBox.Show(item.Name); });
}
}
According to you, the first version is bad practice, because type safety is broken, but the second version does not allow type casting!