title: How to Avoid Explicit Casting using Generics
body: <p>I have a routine which converts all the data in a <code>DataGridView</code> to a corresponding <code>DataTable</code>. I want to extend this method to incorporate the ability to convert just the selected range of the <code>DataGridView</code>. I can clearly do this using basic logic <code>if (bIsSelection) /*Do stuff*/ else /*Do other stuff*/</code> but I would like to use generics here. The problem is that the full <code>DataGridView</code> range is a <code>DataGridViewColumnCollection</code> and the selected range will be a <code>DataGridViewSelectedColumnCollection</code> and C# does not seem to like any conversion between the two, or allow implicit typing in the case of generics.</p>
  
  <p>The first part of my code was</p>
  
  <pre><code>public static DataTable BuildDataSetFromDgv(DataGridView _dataGridView, 
      string strTabName)
  {
      DataTable dt = new DataTable();
  
      dt.TableName = strTabName;
      foreach (DataGridViewColumn col in _dataGridView.Columns)
          dt.Columns.Add(col.DataPropertyName, col.ValueType);
  </code></pre>
  
  <p>and I have attempted</p>
  
  <pre><code>public static DataTable BuildDataSetFromDgv&lt;T&gt;(DataGridView _dataGridView, 
      string strTabName, ICollection&lt;T&gt; _columnColl, ICollection&lt;T&gt; _rowColl)
  {
      DataTable dt = new DataTable();
  
      dt.TableName = strTabName;
      //foreach (DataGridViewColumn col in _dataGridView.Columns)
      foreach (DataGridViewColumn col in _columnColl)
          dt.Columns.Add(col.DataPropertyName, col.ValueType);
  </code></pre>
  
  <p>which does not work due to the implicit conversion, and changing <code>_columnColl</code> to <code>_columnColl as DataGridView[Selected]ColumnCollection</code> defeats the objective. </p>
  
  <p>How do I make this work with generics in this case?</p>
  
  <p>Thanks for your time.</p>