Casting to a generic type

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Paul E Collins

    Casting to a generic type

    I have this method in an inherited DataGridView, but it won't compile
    because the newly added special case is not allowed to cast 'string' to 'T'.

    I know this cast will be valid whenever that code is reached. Is there a way
    to do it, or must I make a separate non-generic method for the string case?

    Eq.


    public T[] GetSelectedColu mnValues<T>(int col)
    {
    T[] values = new T[SelectedRows.Co unt];

    for (int i = 0; i < values.Length; i++)
    {
    if (values is string[]) // this way we can safely deal with DBNull as an
    empty string
    {
    values[i] = (T) SelectedRows[i].Cells[col].Value.ToString ();
    }
    else // general case
    {
    values[i] = (T) SelectedRows[i].Cells[col].Value;
    }
    }

    return values;
    }


  • Paul E Collins

    #2
    Re: Casting to a generic type

    values[i] = (T) SelectedRows[i].Cells[col].Value.ToString ();

    Oh, I posted too soon. I now see that it works with a double cast: (T)
    (object)

    Nasty hack to start with, but there you go.

    Eq.


    Comment

    Working...