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.