I have been looking at the null-propagation operator in C#6 and tried to make it work with the variables of dynamic
type but without success.
Consider the code below, it compiles but CLR throws AccessViolationException
at runtime when the null-propagation is applied to dynamic object.
class SomeType
{
public object SomeProperty { get; set; }
static void Main()
{
var obj = new SomeType() { SomeProperty = "ABCD" };
var p1 = ((dynamic)obj).SomeProperty; //OK, p1 is set to "ABCD"
var p2 = ((dynamic)obj)?.SomeProperty; //AccessViolationException
Console.ReadLine();
}
}
At first I thought that this might be a bug but then I thought about struct
s. Normally you can't apply ?.
operator to a value type variable (because it cannot be null). But you can cast it to dynamic
and then apply the operator. So I changed SomeType
to be struct
and got the same exception.
The question is, it is by design that null-propagation for dynamic variables always is going to throw exception because the underlying object may be a value type?
The AccessViolationException
is pretty ugly anyway, do you get the same one when you run the code?
AccessViolationException is almost always either a compiler bug or a mal-formed PInvoke call.
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