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
221 views
in Technique[技术] by (71.8m points)

c# - Why are short null values converted to int null values for comparing with null?

When I compare nullable short values, the compiler converts them first to integer to make a compare with null. For example, consider this simple code:

short? cTestA;
if (cTestA == null) { ... }

It is converted by the compiler to:

short? CS$0$0001 = cTestA;
int? CS$0$0002 = CS$0$0001.HasValue ? new int?(CS$0$0001.GetValueOrDefault()) : null;
if (!CS$0$0002.HasValue){ ... }

This happens for all .NET versions including .NET 4.

What am I missing here? What is the reason for this double conversion just for a HasValue check?

Follow up

What I expect the compiler to do is to make a simple check with .HasValue, if (cTestA.HasValue){}. At least this is what I do in my code after I discover this conversion.

Why is all this extra code added for such a simple test?

question from:https://stackoverflow.com/questions/9217352/why-are-short-null-values-converted-to-int-null-values-for-comparing-with-null

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

1 Answer

0 votes
by (71.8m points)

Re: your latest update:

This is a bug in the nullable arithmetic optimizer.

The nullable optimizer will remove the unnecessary conversion to int? when you do something like:

short? s = null;
int? x = s + 1;

The unoptimized codegen does the equivalent of:

short? s = null;
int? x;
int? temp = s.HasValue ? new int?((int)s.Value) : new int?();
x = temp.HasValue ? new int?(x.Value + 1) : new int?();

The optimized codegen does the equivalent of:

short? s = null;
int? x;
x = s.HasValue ? new int?((int)s.Value + 1) : new int?();

However, the optimizer contains a bug; we do not remove the unnecessary conversion for equality.

Thanks for bringing it to my attention; we'll fix it for Roslyn. I'm actually about to write the nullable optimizer for Roslyn in the next couple of weeks.

UPDATE: I did write that optimizer, and if you are interested in how it works, I wrote a series of articles on it which starts here:

http://ericlippert.com/2012/12/20/nullable-micro-optimizations-part-one/


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

...