eduesing
eduesing

Reputation: 353

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;

Upvotes: 3

Views: 292

Answers (6)

Eric Lippert
Eric Lippert

Reputation: 659956

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.

Upvotes: 11

Darren
Darren

Reputation: 70718

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.

Upvotes: 1

Albireo
Albireo

Reputation: 11085

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.

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1062494

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.

Upvotes: 7

evanmcdonnal
evanmcdonnal

Reputation: 48076

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.

Upvotes: 2

alex
alex

Reputation: 12654

You can write a lot of things that does not make sence, compiler does not have to point each one of them as a warning.

Upvotes: 1

Related Questions