0

I'm pretty new to C#. While attempting to set a local variable value, I'm running into a NullReferenceException. It appears that the Buyer object is null, which I'm assuming is why it can't figure out the Buyer.Username value. What I'm not sure about is how to check if Buyer is not null AND that the Buyer.Username has a non-null value (in the most simple way possible). Unfortunately, I'm using C# 7.3 which doesn't appear to have support for the ?? operator.

BuyerUserName = string.IsNullOrEmpty(model.Transactions[i].Buyer.Username) ? "" : model.Transactions[i].Buyer.Username
Matthew Walk
  • 1,014
  • 2
  • 16
  • 36
  • 1
    Well generally null-coalescing operators like `??` and `?.` reduce to if statements during compile time, so maybe you could just write them yourself? IE `if (Buyer is not null && Buyer.Username is not null)` – Jakob Lovern Sep 08 '22 at 20:07
  • *"if Buyer is not null AND that the Buyer.Username has a non-null value"* - The semantics of that description strongly imply the exact nature of an `if` condition. What have you tried and what didn't work? (Also... *"I'm using C# 7.3 which doesn't appear to have support for the ?? operator."* - On what do you base that?) – David Sep 08 '22 at 20:08
  • 2
    I'm not sure I get your question. What exactly is stopping you from writing an `if` statement? You know that not everything has to be a one-liner? In fact your one-liner already is hard to read. You sure you want to make it worse? – freakish Sep 08 '22 at 20:09
  • 1
    Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Progman Sep 08 '22 at 20:16

1 Answers1

2

Both ?? and ?. were introduced in C# 6, so you can use them:

BuyerUserName = model.Transactions[i].Buyer?.Username ?? string.Empty;

But even without that, there is nothing wrong with taking more than one line to do something, and you could just use an if statement:

var buyer = model.Transactions[i].Buyer;
if (buyer != null && buyer.Username != null)
    BuyerUserName = buyer.Username;
else
    BuyerUserName = string.Empty;
Etienne de Martel
  • 34,692
  • 8
  • 91
  • 111
  • 1
    +1 for saying _"there is nothing wrong with taking more than one line to do something"_. Too many people seem to think that putting a page of fluent API code into a single statement is a good idea. Temporary variables cost nothing in your production code (the JITter will nearly always optimize them away in a release build). What they do is increase debug-ability immensely; you get to see what is null and not-null in the debugger. – Flydog57 Sep 08 '22 at 22:30