Why casting using the "as" operator causes a cast object to be null with C # dynamics

For instance,

Suppose group.SupportedProducts is ["test", "hello", "world"]

var products = (string[]) group.SupportedProducts; 

leads to the fact that "products" correctly represent a string array that contains the above 3 elements - "test", "hello" and "world"

but

 var products= group.SupportedProducts as string[]; 

results in zero product values.

+4
source share
1 answer

Presumably group.SupportedProducts is actually not a string[] , but it is what supports custom conversion to string[] .

as never causes custom conversions, while casting does.

An example 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); } } 
+9
source

All Articles