I am making a generic class where I add data by console to a two-dimensional array. The problem arises when adding the data by console since, being a generic class, the type of data to be added is not specified.
class Array2D<T>
{
//Variables
private T[,] datos;
//Metodo Constructor
public Array2D(int x, int y)
{
datos = new T[x, y];
}
// metodo agregar datos
public void Agregar()
{
for (int f = 0; f < datos.GetLength(0); f++)
{
for (int c = 0; c < datos.GetLength(1); c++)
{
Console.Write($"Introduce el dato ({f},{c}): ");
datos[f, c] = T.Parse(Console.ReadLine()); // Error CS0119 T es parámetro de tipo que no es valida en el contexto indicado
}
}
}
//metodo imprimir array
public void Imprimir()
{
for (int f = 0; f < datos.GetLength(0); f++)
{
for (int c = 0; c < datos.GetLength(1); c++)
{
Console.Write(datos[f, c] + " ");
}
Console.WriteLine();
}
}
I have tried to do an explicit conversion (casting) but it has not worked. When trying to compile it gives me Error CS0119 T is a type parameter that is not valid in the indicated context. On the other hand, if I want to make an array of type string, I would run into the same problem since it cannot be implicitly converted from type string to T. What could I do to solve it? Thanks.
namespace ArrayBidimensional
{
class Program
{
static void Main(string[] args)
{
Array2D<int> array1 = new Array2D<int>(3, 3);
array1.Agregar();
}
}
}
The problem is that you cannot in any way ensure that the generic type
T
has a static method namedParse
. That's why your code doesn't compile. The compiler does not know how to convert an object of typeString
to an object of typeT
and cannot ensure that itParse
exists.To solve this, it is necessary to constrain the type
T
by having it implement an interface that allows changing the type ofstring
aT
. Since you're working with numbers, force the type T to implement the interfaceIConvertible
, most numeric types do. Then useConvert.ChangeType
to convert from typestring
to typeT
.In any case, in my opinion, I don't think that the class
Array2D<T>
should have the responsibility to read its own data in the console and parse it. That should be delegated to another outer class.