Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

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.

like image 256
govin Avatar asked Jan 15 '23 05:01

govin


1 Answers

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);
    }
}
like image 188
Jon Skeet Avatar answered Jan 16 '23 19:01

Jon Skeet