Click here to Skip to main content
15,885,216 members
Articles / Programming Languages / C#
Tip/Trick

An Oddity of the ?? Operator (C#)

Rate me:
Please Sign up or sign in to vote.
4.68/5 (7 votes)
20 Jan 2022CPOL2 min read 14.8K   4   33
The ?? operator is odd when combined with exceptions - It helps assignments but not non-assignments. Why?
This is a "quick complaint" of a feature that I consider very annoying which Visual Studio is trying to make us use, when the feature isn't really making code more readable, it is just making it "more compact" in just half the situations.

This is how we would probably do things in old C# code:

C#
if (input == null)
  throw new ArgumentNullException("input");

_input = input;

Now, we can reduce the entire thing to just:

C#
_input = input ?? throw new ArgumentNullException("input");

The odd thing is that if I am not assigning input to _input, the old code will just lose code while the new code needs to go back to the old code, becoming:

C#
if (input == null)
  throw new ArgumentNullException("input");

With the new ?? operator, we can't just remove the _input = . That will simply not compile.

Isn't that odd?

Why can't just input ?? throw new ArgumentNullException("input"); mean the same as...

C#
if (input == null)
  throw new ArgumentNullException("input");

... when we are not assigning anything to a variable?

I understand it would make no sense for non-assigments if we were just using ?? to read a variable, but when there is an exception being thrown or a method being called, why not?

It should work as an "if replacement" in those circumstances too, don't you think?

Expressions vs Statements - Does it matter?

I got an answer that the reason ?? works in one case and not the other is because it is an operator and only works as part of expressions, not statements.

Although there is some truth in there, the ?. is also an operator and works on bare statements. So, assuming throw is usually a statement, operator ?? should possibly work with it too.

Also I see that even in MSDN (for example this one about async enumerators) they compare what we write, and what the code is really compiled into (so, we can say that one expression is just a synctactic sugar for another).

That's why I will do this comparison:

C#
obj ?? ObjIsNull(); // Makes sense
obj ?? throw new Exception(); // Makes sense
obj ?? x; // Doesn't make any sense.

var y = obj ?? x; // This one works right now.

All of those can actully be seen as synctactic sugar for:

C#
if (obj == null)
  ObjIsNull(); // Should compile fine.

if (obj == null)
  throw new Exception(); // Should compile fine.

if (obj == null)
  x; // Should cause a compile-time error.


var y = obj;
if (y == null)
  y = x; // Should also work fine.

So, I believe that independenty if we can justify why it doesn't work in statements, the operator ?? is perfectly applicable in statements when we have method calls or when throwing exceptions.

This is Not an Article

Just to make it obvious, this is not an article, that's why I didn't put introduction, background and things like that. Also, I will not discuss coding styles, like using { and } on every if (which actually makes the presented problem even worse) or using the nameof() keyword.

This is just a "quick complaint" of a feature that I consider very annoying that Visual Studio is trying to make us use, when the feature isn't really making code more readable, it is just making it "more compact" in just half the situations.

History

  • 20th January, 2022: Added Expression vs Statements topic
  • 19th January, 2022: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Microsoft
United States United States
I started to program computers when I was 11 years old, as a hobbyist, programming in AMOS Basic and Blitz Basic for Amiga.
At 12 I had my first try with assembler, but it was too difficult at the time. Then, in the same year, I learned C and, after learning C, I was finally able to learn assembler (for Motorola 680x0).
Not sure, but probably between 12 and 13, I started to learn C++. I always programmed "in an object oriented way", but using function pointers instead of virtual methods.

At 15 I started to learn Pascal at school and to use Delphi. At 16 I started my first internship (using Delphi). At 18 I started to work professionally using C++ and since then I've developed my programming skills as a professional developer in C++ and C#, generally creating libraries that help other developers do their work easier, faster and with less errors.

Want more info or simply want to contact me?
Take a look at: http://paulozemek.azurewebsites.net/
Or e-mail me at: paulozemek@outlook.com

Codeproject MVP 2012, 2015 & 2016
Microsoft MVP 2013-2014 (in October 2014 I started working at Microsoft, so I can't be a Microsoft MVP anymore).

Comments and Discussions

 
Question.Net 6 does add a 1-liner: ArgumentNullException.ThrowIfNull(input) Pin
rhyous26-Jan-22 11:11
rhyous26-Jan-22 11:11 
AnswerRe: .Net 6 does add a 1-liner: ArgumentNullException.ThrowIfNull(input) Pin
Paulo Zemek26-Jan-22 11:44
mvaPaulo Zemek26-Jan-22 11:44 
QuestionIt's how operators are supposed to work Pin
_groo_24-Jan-22 10:38
_groo_24-Jan-22 10:38 
AnswerRe: It's how operators are supposed to work Pin
Paulo Zemek24-Jan-22 11:24
mvaPaulo Zemek24-Jan-22 11:24 
GeneralMy vote of 5 Pin
Ștefan-Mihai MOGA23-Jan-22 20:28
professionalȘtefan-Mihai MOGA23-Jan-22 20:28 
QuestionWhen I was younger ... Pin
Member 1194113121-Jan-22 10:22
Member 1194113121-Jan-22 10:22 
AnswerRe: When I was younger ... Pin
Paulo Zemek21-Jan-22 11:29
mvaPaulo Zemek21-Jan-22 11:29 
GeneralRe: When I was younger ... Pin
Member 1194113121-Jan-22 11:51
Member 1194113121-Jan-22 11:51 
GeneralRe: When I was younger ... Pin
Paulo Zemek21-Jan-22 12:37
mvaPaulo Zemek21-Jan-22 12:37 
AnswerRe: When I was younger ... Pin
haughtonomous24-Jan-22 1:45
haughtonomous24-Jan-22 1:45 
Questionthat is a good idea Pin
codeprojectddx20-Jan-22 17:40
codeprojectddx20-Jan-22 17:40 
QuestionSeveral things going on here, lets deconstruct this question Pin
Stacy Dudovitz20-Jan-22 9:20
professionalStacy Dudovitz20-Jan-22 9:20 
OK, so the immediate answer is ?? or the null coalescing operator has two operands. As such, you would have to supply two parameters.

I think, however, in reading the responses your question raises a larger question, or questions, that is/are alluded to, namely:
  1. What or how should we handle parameter checking before we begin to execute code inside a method i.e. what do best practices dictate?
  2. Do we need all the baggage when trying to achieve a simple objective?
Here's where lore weighs us down. The notion of throwing exceptions on null or invalid arguments, or indeed, in general is so ingrained in application developers I sometimes wonder if the notion of an exception is lost that it should be, well.... exceptional. Anyone who develops code in the embedded world will immediately pick up on this... choose your RTOS, we pretty much turn off exception handling support in whatever flavor of the language you are using (typically some version of Eclipse C++).

My point here is this... Microsoft, in its zeal to expand the power of the null coalescing operator to allow throwing exceptions as an operand has now propagated catching exceptions in ways that are difficult to trace and debug, and frankly manage. Anyone who has developed in TPL with parallel tasks and aggregate exception handling across synchronization contexts will immediate recognize what I am talking about... its a hot mess.

Best practices dictates writing exception free/lock free code whenever and where ever possible. That means using exceptions in exceptional cases.

Lets go back to your example, the classic parameter check. Context is everything. Lets say its a name in a database or even a primary key. Maybe that should halt current operation, but that's hardly an exception. I would favor this:
if (arg == null)
{
    return null;
}

// continue method execution

If, however, this is a method that writes, say, a block of bytes to a sector onto non-volatile flash memory or a USB device, and the pointer is null, then in this case, yeah, that's a real exception. Houston, we have a problem. We probably want to bail.

I think you get the idea.

FWIW, I think it's a good question.
AnswerRe: Several things going on here, lets deconstruct this question Pin
Paulo Zemek20-Jan-22 9:52
mvaPaulo Zemek20-Jan-22 9:52 
GeneralRe: Several things going on here, lets deconstruct this question Pin
Stacy Dudovitz31-Jan-22 10:30
professionalStacy Dudovitz31-Jan-22 10:30 
QuestionNull coalescing operator ?? Pin
V.Lorz20-Jan-22 5:01
V.Lorz20-Jan-22 5:01 
QuestionAn oddity of ?? in PHP Pin
John Bevan20-Jan-22 1:48
John Bevan20-Jan-22 1:48 
AnswerRe: An oddity of ?? in PHP Pin
Paulo Zemek20-Jan-22 9:47
mvaPaulo Zemek20-Jan-22 9:47 
AnswerRe: An oddity of ?? in PHP Pin
David On Life24-Jan-22 8:40
David On Life24-Jan-22 8:40 
QuestionFood for Thought Pin
AllenR20-Jan-22 0:16
professionalAllenR20-Jan-22 0:16 
QuestionThe answer is... Pin
wkempf19-Jan-22 2:54
wkempf19-Jan-22 2:54 
AnswerRe: The answer is... Pin
Paulo Zemek19-Jan-22 7:47
mvaPaulo Zemek19-Jan-22 7:47 
GeneralRe: The answer is... Pin
wkempf19-Jan-22 9:24
wkempf19-Jan-22 9:24 
GeneralRe: The answer is... Pin
Paulo Zemek19-Jan-22 9:35
mvaPaulo Zemek19-Jan-22 9:35 
GeneralRe: The answer is... Pin
wkempf19-Jan-22 9:43
wkempf19-Jan-22 9:43 
GeneralRe: The answer is... Pin
Paulo Zemek19-Jan-22 9:57
mvaPaulo Zemek19-Jan-22 9:57 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.