Water Cooler v2
Water Cooler v2

Reputation: 33880

Cast generic type parameter into array

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);
  }
}

Upvotes: 7

Views: 2757

Answers (3)

Nick Freeman
Nick Freeman

Reputation: 1411

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);
  }
}

Upvotes: 3

Yuck
Yuck

Reputation: 50865

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.

Upvotes: 9

JohnB
JohnB

Reputation: 13743

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.

Upvotes: 2

Related Questions