Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast generic type parameter into array

Tags:

c#

c#-4.0

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);
  }
}
like image 588
Water Cooler v2 Avatar asked Mar 29 '13 14:03

Water Cooler v2


3 Answers

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.

like image 195
Yuck Avatar answered Nov 07 '22 16:11

Yuck


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);
  }
}
like image 33
Nick Freeman Avatar answered Nov 07 '22 16:11

Nick Freeman


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.

like image 2
JohnB Avatar answered Nov 07 '22 15:11

JohnB