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.

2
  • 2
    Try : string.Join(",", obj.ToArray()); Commented May 25, 2021 at 9:54
  • 2
    @jdweng: That won't compile as-is. Commented May 25, 2021 at 9:57

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

5 Comments

object? as parameter, will it actually compile?
@JamshaidK.: i don't use C#8 features yet but in Linqpad it just gives a warning. I just adapted OP's code here. You will get the same in the provided fiddle if you change it.
@JamshaidK.: Changed the fiddle now to show that it compiles and runs but with that warning.
This gives an error if you are using .net version less than 5.0.
@JamshaidK.: but it's OP's code so it seems he uses .NET 5. It's not my idea ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.