简体   繁体   中英

Why doesn't obj ?? null cause an compiler warning

In the case where reference type is coalesced with null, why isn't this a compiler warning in the C# compiler? Is there any case where this makes sense?

obj2 = obj ?? null;

You should read my essay on the subject .

Briefly: in order for a compiler warning to exist it has to be:

  1. Thought of
  2. Cheap to implement
  3. Almost always wrong
  4. Reasonably typed by accident
  5. Eliminatable
  6. Rare
  7. Only capable of being done by the compiler
  8. Not obvious upon testing

Your proposed warning does not meet requirements 1 and 4. You are, to my knowledge, the first person to think of this, and therefore it cannot be a warning because no one on the compiler team thought of it. And it is not likely to be typed by accident, so why should it be a warning? Warnings are there to tell you when you mistyped something that is likely to be mistyped. It also fails requirement 3, since the code is not obviously wrong , it's just needlessly complicated . The compiler does not give warnings for x * 1 where x is an integer either.

It makes sense , it just isn't very useful.

Neither is:

i = i + 0;

But the compiler doesn't complain about that either. Why should it? The compiler does what it is told, as long as your request is syntactically correct - which it is.

Your example doesn't exactly make sense but something like this does;

d = a ?? b ?? c ?? null;

Here, I'm saying taking the first non null value of the three, if they're all null then just take null.

你可以写很多没有意义的东西,编译器不必每一个都点作为警告。

Although the statement is not very useful, why would it warn you?

If obj is not null, obj2 is assigned to obj . Else obj2 is assigned to null . This is perfectly legal.

As Eric Lippert said ,

we try to reserve warnings for only those situations where we can say with almost certainty that the code is broken, misleading or useless

So warnings are used for code which, while being syntactically correct, can lead to real problems.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM