I have a generic class and I take its type as a parameter type e.g. int
for a method in my class like below:
public class UnlimitedGenericArray<T>
{
private void InsertItem(T item)
{
this.array[0] = item;
}
}
Now, when I want to invoke the InsertItem()
from a console application for example how can I know the argument's type at runtime?
static void Main(string[] args)
{
UnlimitedGenericArray<int> oArray = new UnlimitedGenericArray<int>();
while(true)
{
var userInput = Console.Readline();
oArray.InsertItem(userInput);
}
}
I can write InsertItem(object item)
instead and then cast in the method like below:
private void InsertItem(object item)
{
this.array[0] = (T)Convert.ChangeType(item, typeof(T));
}
But this is probably not a good practice. I also need to know the type of argument at client so that I can parse there and then invoke the method. I am new to Generics so help me out here please.
InsertItem(5)
will compile just fine.T
resolves toint
.main()
and I am adding the class to my project. I need to invoke it because this is only way user can insert an item in an array.InsertItem(5)
will compile fine but I am reading the user inputConsole.Readline()
so if myInsertItem
takesint
as its argument type then it would saycannot convert from string to int
.this.array
is generic array type inside the class I mentioned aboveprivate T[] array = new T[0];
You probably figured it but I am trying to build a class that will use only arrays to store undetermined number of items of user defined type.List<T>
works.