Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null propagation operator and dynamic variable

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 structs. 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?

like image 976
nan Avatar asked Jun 12 '14 22:06

nan


1 Answers

AccessViolationException is almost always either a compiler bug or a mal-formed PInvoke call.

like image 180
Jonathan Allen Avatar answered Oct 22 '22 11:10

Jonathan Allen