3

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); } 
2
  • Don't mix backquotes and four-space indent. Only one of those is required to mark up code. Commented Apr 23, 2010 at 9:30
  • 1
    As soon as 'edited by Jon Skeet' appeared ... Commented Apr 23, 2010 at 9:31

1 Answer 1

3

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)); 
Sign up to request clarification or add additional context in comments.

4 Comments

@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: 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.
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: 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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.