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.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With