Why does casting using "as" operator result in the casted object being null with C# dynamics

.net, c#

Solution

Presumably `group.SupportedProducts` isn't actually a `string[]`, but it's something which supports a custom conversion to `string[]`.

`as` never invokes custom conversions, whereas casting does.

Sample to demonstrate this:

using System;

class Foo
{
    private readonly string name;

    public Foo(string name)
    {
        this.name = name;
    }

    public static explicit operator string(Foo input)
    {
        return input.name;
    }
}

class Test
{
    static void Main()
    {
        dynamic foo = new Foo("name");
        Console.WriteLine("Casting: {0}", (string) foo);
        Console.WriteLine("As: {0}", foo as string);
    }
}

Problem

For example, Lets say group.SupportedProducts is ["test", "hello", "world"] ``` var products = (string[]) group.SupportedProducts; ``` results in "products" correctly being a string array which contains the above 3 elements - "test", "hello" and "world" However, ``` var products= group.SupportedProducts as string[]; ``` results in products being null.

Original source