471,310 Members | 1,466 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,310 software developers and data experts.

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[] GetSelectedColumnValues<T>(int col)
{
T[] values = new T[SelectedRows.Count];

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;
}
Aug 22 '08 #1
1 1024
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.
Aug 22 '08 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

231 posts views Thread by Brian Blais | last post: by
35 posts views Thread by ytrama | last post: by
1 post views Thread by Mark McDonald | last post: by
8 posts views Thread by Kris Jennings | last post: by
7 posts views Thread by S. Lortan | last post: by
3 posts views Thread by =?Utf-8?B?TWlydHVs?= | last post: by
reply views Thread by rosydwin | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.