Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
162 views
in Technique[技术] by (71.8m points)

c# - Casting with conditional/ternary ("?:") operator

I have this extract of C# source code:

object valueFromDatabase;
decimal result;
valueFromDatabase = DBNull.Value;

result = (decimal)(valueFromDatabase != DBNull.Value ? valueFromDatabase : 0);
result = (valueFromDatabase != DBNull.Value ? (decimal)valueFromDatabase : (decimal)0);

The first result evaluation throws an InvalidCastException whereas the second one does not. What is the difference between these two?

question from:https://stackoverflow.com/questions/1171717/casting-with-conditional-ternary-operator

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

UPDATE: This question was the subject of my blog on May 27th 2010. Thanks for the great question!

There are a great many very confusing answers here. Let me try to precisely answer your question. Let's simplify this down:

object value = whatever;
bool condition = something;
decimal result = (decimal)(condition ? value : 0);

How does the compiler interpret the last line? The problem faced by the compiler is that the type of the conditional expression must be consistent for both branches; the language rules do not allow you to return object on one branch and int on the other. The choices are object and int. Every int is convertible to object but not every object is convertible to int, so the compiler chooses object. Therefore this is the same as

decimal result = (decimal)(condition ? (object)value : (object)0);

Therefore the zero returned is a boxed int.

You then unbox the int to decimal. It is illegal to unbox a boxed int to decimal. For the reasons why, see my blog article on that subject:

Representation and Identity

Basically, your problem is that you're acting as though the cast to decimal were distributed, like this:

decimal result = condition ? (decimal)value : (decimal)0;

But as we've seen, that is not what

decimal result = (decimal)(condition ? value : 0);

means. That means "make both alternatives into objects and then unbox the resulting object".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...