Using C# 10 I am trying to convert an IEnumerable<String>?
to an IEnumerable<T>
:
IEnumerable<String>? inputs = getValues();
if (inputs is null)
return false;
Type type = typeof(List<>).MakeGenericType(typeof(T));
IList? outputs = (IList?)Activator.CreateInstance(type);
TypeConverter converter = TypeDescriptor.GetConverter(typeof(T));
if (converter is null || outputs is null || !converter.CanConvertFrom(typeof(String)))
return false;
foreach (String input in inputs) {
if (converter.IsValid(input))
outputs.Add(converter.ConvertFromString(input));
}
var texpression = new TExpression<T>(outputs);
I am getting an error on last line even if I use outputs.ToList()
:
Cannot convert from 'System.Collections.IList' to 'System.Collections.Generic.IEnumerable<T>'
The TExpression
constructor is:
public TExpression(IEnumerable<T> values) {
Values = values;
}
I tried to change the types of my conversion code but I always end with an error somewhere.
How can I fix this so I can use the constructor without changing the constructor?
Update
Using the following:
IList<T> outputs = (IList<T>)Activator.CreateInstance(type);
...
foreach (string input in inputs) {
if (converter.IsValid(input))
outputs.Add((T)converter.ConvertFromString(input));
}
I get the warning (I am using <Nullable>enable</Nullable>
):
Converting null literal or possible null value to non-nullable type.
T
can be a nullable type (Int32?) or a non nullable type (Int32).
I could change the code line to:
T? output = (T?)converter.ConvertFromString(input);
This fixes the warning but is it correct?
What if T is a non nullable type?
CodePudding user response:
Since you actually now the type of collection you can use it:
IList<T> outputs = (IList<T>)Activator.CreateInstance(type);
...
foreach (string input in inputs) {
if (converter.IsValid(input))
outputs.Add((T)converter.ConvertFromString(input)); // here also
}