If I know that a certain generic type parameter is an array, how do I convert it into an array or an IEnumerable
so I can see its items? For e.g.
public class Foo<T>
{
public T Value { get; set; }
public void Print()
{
if (Value.GetType().IsArray)
foreach (var item in Value /*How do I cast this to Array or IEnumerable*/)
Console.WriteLine(item);
}
}
Try something like this:
public void Print()
{
var array = Value as Array;
if (array != null)
foreach (var item in array)
Console.WriteLine(item);
}
The as keyword:
The as operator is like a cast operation. However, if the conversion isn't possible, as returns null instead of raising an exception.
or you could constrain your type parameter
public class Foo<T> where T : IEnumerable
{
public T Value { get; set; }
public void Print()
{
foreach (var item in Value)
Console.WriteLine(item);
}
}
Try
foreach (var item in (object []) Value)
As, however, you only make use of the fact that you can enumerate Value
, you might prefer
var e = Value as IEnumerable;
if (e == null) return;
foreach (var item in e) Console.WriteLine (item);
This improves encapsulation and makes it unnecessary to change your code if you switch, e.g., from an array to a list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With