2

If object is array I want to return string representation of it as follows:

using System;
using System.Linq;
using Xunit;
using Xunit.Abstractions;

namespace Tests.UnitTests
{
    enum TestEnum {
        A,
        B
    }

    public class MyClass {

        private readonly ITestOutputHelper _testOutputHelper;

        public static string ObjectToString(object? obj) {
            if (obj?.GetType().IsArray == true)
            {
                return string.Join(",", obj); // <-- does not work, returns "Tests.UnitTests.TestEnum[]"
                return string.Join(",", ((object[]) obj).AsEnumerable()); // <-- does not work, throws "Unable to cast object of type 'Tests.UnitTests.TestEnum[]' to type 'System.Object[]"
                return string.Join(",", ((Enum[]) obj).AsEnumerable()); // <-- does not work, throws "Unable to cast object of type 'Tests.UnitTests.TestEnum[]' to type 'System.Enum[]'"
            }
            return obj?.ToString() ?? "<unknown>";
        }

        public MyClass(ITestOutputHelper testOutputHelper)
        {
            _testOutputHelper = testOutputHelper;
        }

        [Fact]
        public void Test() {
            var val = new TestEnum[] { TestEnum.A, TestEnum.B };
            var result = ObjectToString(val);
            _testOutputHelper.WriteLine($"RESULT: {result}");
        }
    }
}

Generally I need to check if obj is array, cast it to "any" array and map it's values to strings. How can I do it? In example I used enum but I want to make it work for array of any type of value, just want to invoke ToString() on each array elements and join result.

user606521
  • 14,486
  • 30
  • 113
  • 204

1 Answers1

7

You can try-cast to IEnumerable and use Cast<Object>

public static string ObjectToString(object? obj)
{
    if (obj is IEnumerable enumerable)
    {
        return string.Join(",", enumerable.Cast<Object>()); 
    }
    return obj?.ToString() ?? "<unknown>";
}

.Net fiddle

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • 1
    `object?` as parameter, will it actually compile? – Jamshaid K. May 25 '21 at 10:03
  • @JamshaidK.: i don't use C#8 features yet but in Linqpad it just gives a [warning](https://stackoverflow.com/questions/55492214/the-annotation-for-nullable-reference-types-should-only-be-used-in-code-within-a). I just adapted OP's code here. You will get the same in the provided fiddle if you change it. – Tim Schmelter May 25 '21 at 10:06
  • @JamshaidK.: Changed the [fiddle](https://dotnetfiddle.net/EwyHnL) now to show that it compiles and runs but with that warning. – Tim Schmelter May 25 '21 at 10:24
  • This gives an error if you are using .net version less than 5.0. – Jamshaid K. May 25 '21 at 10:54
  • 1
    @JamshaidK.: but it's OP's code so it seems he uses .NET 5. It's not my idea ;) – Tim Schmelter May 25 '21 at 11:12