Null propagation operator and dynamic variable

本小妞迷上赌 提交于 2019-12-04 16:24:03

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/24194790/null-propagation-operator-and-dynamic-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!