tags:

views:

52

answers:

1

I am trying to use generic for the first time and trying to typecast my result returned from database to programmer defined data type. How can I do this.

dsb.ExecuteQuery("DELETE FROM CurrencyMaster WHERE CurrencyMasterId="
        + returnValueFromGrid<int>(getSelectedRowIndex(), "CurrencyMasterId"));

private T returnValueFromGrid<T>(int RowNo, string ColName)
{
    return Convert.ChangeType(dgvCurrencyMaster.Rows[RowNo].Cells[ColName].Value, T);
}
+3  A: 

You're trying to use T as a value - you want the type T represents, and then you'll need a cast as well:

object value = dgvCurrencyMaster.Rows[RowNo].Cells[ColName].Value;
return (T) Convert.ChangeType(value, typeof(T));
Jon Skeet
@Jon: Thx it worked, I did't thought that there is typeof also. I was using getType. I need 1 more favour here plz. Where can i use generic in my real time applications. Is it a proper use of generic or generic is used in some different situations ?
Shantanu Gupta
@Shantanu: I'm not really sure what you're asking. Generics are indeed used in all kinds of different situations. Collections are the most common use, but far from the only one.
Jon Skeet
@Jon: I am trying to get some data from database base which have different different data types say string, int, binary etc which programmer will be specifying after looking what value he/she need to display then accordingly he will be typecasting and using. Is it a one of the use or should it be done from application user rather than programmer
Shantanu Gupta
@Shantanu: In this case I don't think there's likely to be much benefit in having a generic method over just casting - you'll still need to specify the type, after all.
Jon Skeet