开发者

What is the inner difference between (MyType)SomeObj.Property1 and (MyType)(SomeObj.Property1) in C#?

It's probably very lame question, but I found no references in C# specification about round brackets. Please point me to spec or msdn if answer on that question will be obvious.

What is the inner difference between (MyType)SomeObj.Property1 and (MyType)(SomeObj.Property1) in C# ?

AFAIK, in first case ( (x)SomeObj.Property1 cast ) - it will be the reference of concrete type (MyType) to Property1. In second case, such reference will execute get accessor SomeObj.get_Property1. And it eventually could lead to subtle errors if get accessor have any side effects (and its often - do have ones)

Could anyone point me to exact documentation where such behaviour specified ?

Updated: Thank you for pointing. And I deeply apologize about such dumb question - after posting this question, I found a typo 开发者_开发知识库in example I fiddle with and thus realized that second case behaviour was not based on code I tried to compile, but on previously compiled completely different code. So my question was initially based on my own blindness ...


They are equivalent. This is determined by the operator precedence rules in the C# language, chapter 7.2.1 in the C# Language Specification:

What is the inner difference between (MyType)SomeObj.Property1 and (MyType)(SomeObj.Property1) in C#?

The . operator is at the top in this list, the cast operator is the 2nd in the list. The . operator "wins". You will have use parentheses if you need the cast because Property1 is a property of the MyType class:

 ((MyType)SomeObj).Property1


There is absolutely no difference. The . operator binds more tightly than the typecast operator, so the extra parentheses make no difference. See here for details of operator precedence; the operators in question are in the first two groups.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜