tags:

views:

74

answers:

1

I am very new to generics and trying to implement it. How can i use it here.

   private T  returnValueFromGrid(int RowNo, int ColNo) 
        {
            return (T) dgvCurrencyMaster.Rows[RowNo].Cells[ColNo].Value;
        }

I am trying to convert below value to generic type and then return it.

dgvCurrencyMaster.Rows[RowNo].Cells[ColNo].Value

Here i need to know two things. How to do the above problem and how to use this in my code. Please provide some eg.

EDIT

It is giving me error Error The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?

+4  A: 

It's simply:

private T returnValueFromGrid<T>(int RowNo, int ColNo)
{
    return (T)dgvCurrencyMaster.Rows[RowNo].Cells[ColNo].Value;
}

You use T in the same way as if it was a type name.

Having said that, if this is all you're doing then you're not really getting any benefit from generics, because either way the caller of your method has to specify the type. That is, with generics it looks like this:

var x = returnValueFromGrid<SomeType>(1, 2);

Without generics it would look like this:

var x = (SomeType)returnValueFromGrid(1, 2);

You're simply pushing the cast down into the method, but not really saving any work - either for the programmer or for the CPU.

Evgeny
@Evgeny: Thx, this worked out. Could you please provide some description why T has been used on both side of function. What they are doing etc. If you could provide some reference regarding the same , that would be very helpfull.
Shantanu Gupta
On the right side `<T>` says "this function has a type argument named T". The `T` on the left is simply the return type - which happens to be the type argument declared later.
Evgeny
@Evgeny: Thx I got u.
Shantanu Gupta