I write a large static method that takes a generic as a parameter argument. I call this method, and the framework throws a System.InvalidProgramException. This exception is thrown even before the first line of the method is executed.
I can create a static class which takes the generic argument, and then make this a method of the static class, and everything works fine.
Is this a .NET defect, or is there some obscure generic rule I'm breaking here?
For the sake of completeness, I've included the method which fails, and the method which passes. Note that this uses a number of other classes from my own library (eg GridUtils), and these classes are not explained here. I don't think the actual meaning matters: the question is why the runtime crashes before the method even starts.
(I'm programming with Visual Studio 2005, so maybe this has gone away in Visual Studio 2008.)
This throws an exception before the first line is invoked:
private delegate void PROG_Delegate<TGridLine>(DataGridView dgv, IEnumerable<TGridLine> gridLines, string[] columns);
public static void PopulateReadOnlyGrid<TGridLine>(DataGridView dgv, IEnumerable<TGridLine> gridLines, string[] columns)
{
if (dgv.InvokeRequired)
{
dgv.BeginInvoke
(
new PROG_Delegate<TGridLine>(PopulateReadOnlyGrid<TGridLine>),
new object[] { dgv, gridLines, columns }
);
return;
}
GridUtils.StatePreserver statePreserver = new GridUtils.StatePreserver(dgv);
System.Data.DataTable dt = CollectionHelper.ConvertToDataTable<TGridLine>((gridLines));
dgv.DataSource = dt;
dgv.DataMember = "";
dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
GridUtils.OrderColumns<TGridLine>(dgv, columns);
statePreserver.RestoreState();
dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
}
This works fine:
public static class Populator<TGridLine>
{
private delegate void PROG_Delegate(DataGridView dgv, IEnumerable<TGridLine> gridLines, string[] columns);
public static void PopulateReadOnlyGrid(DataGridView dgv, IEnumerable<TGridLine> gridLines, string[] columns)
{
if (dgv.InvokeRequired)
{
dgv.BeginInvoke
(
new PROG_Delegate(PopulateReadOnlyGrid),
new object[] { dgv, gridLines, columns }
);
return;
}
GridUtils.StatePreserver statePreserver = new GridUtils.StatePreserver(dgv);
System.Data.DataTable dt = CollectionHelper.ConvertToDataTable<TGridLine>((gridLines));
dgv.DataSource = dt;
dgv.DataMember = "";
dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
GridUtils.OrderColumns<TGridLine>(dgv, columns);
statePreserver.RestoreState();
dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
}
}