How to use certain properties of a type parameter in a generic method

  • Thread starter Thread starter MesPia
  • Start date Start date
M

MesPia

Guest
I am trying to write a generic method in which one parameter can be either a byte[] or a string. Inside the method I want to use the Length property which is present for a byte[] or string as well as an indexer which also works for byte[] and string. However, I don't know how to get around the compiler message 'T does not contain a definition for Length...' and 'Cannot apply indexing with [] to an expression of type T'. A code example is shown below. Please help.
static void DisplayItems<T> (T obj, int itemsPerRow)
{
int index = 0;
int nextItem;

while (index < obj.Length)
{
for (int itemsInRow = 0; itemsInRow < itemsPerRow; itemsInRow++)
{
nextItem = index + itemsInRow;

if (nextItem < obj.Length)
{
Write (obj[nextItem]);
}
else
break;
}

WriteLine ();

index += itemsPerRow;
}
}



MesPia

Continue reading...
 
Back
Top