I have a method like below ↓
static T GetItemSample<T>() where T : new ()
{
if (T is string[])
{
string[] values = new string[] { "col1" , "col2" , "col3"};
Type elementType = typeof(string);
Array array = Array.CreateInstance(elementType, values.Length);
values.CopyTo(array, 0);
T obj = (T)(object)array;
return obj;
}
else
{
return new T();
}
}
There is an error when I invoke the method like ↓
string[] ret = GetItemSample<string[]>();
Is anybody could told me how to use the method when the param is string[] ?
thks .
The first error (
'T' is a 'type parameter' but is used like a 'variable') is thatT is string[]won’t work. You could usetypeof(string[])==typeof(T)The second error (
'string[]' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'UserQuery.GetItemSample<T>()') is thatstring[]has no default constructor but the generic constraint requires it to have one.The disadvantage of this code is that it throws an error at runtime if
Thas no default constructor instead of at compile-time.