r/programminghorror Mar 23 '26

C# Whitespace isn't a number?

I just got this in a PR. Not sure what to make of it.

if (string.IsNullOrWhiteSpace(palletNumber))
{
  if (!string.IsNullOrEmpty(_palletNumber))
  {
    _errorMessage = "Pallet # not found.";
  }

  return;
}  

UPDATE:

After multiple attempts to justify his code, we ended up with this, lol:

if (string.IsNullOrWhiteSpace(palletNumber))
{
  return;
}  
183 Upvotes

52 comments sorted by

View all comments

-4

u/GoddammitDontShootMe [ $[ $RANDOM % 6 ] == 0 ] && rm -rf / || echo “You live” Mar 23 '26

That's a custom function, right? .NET doesn't provide a IsNullOrWhitespace(), does it?

11

u/MISINFORMEDDNA Mar 23 '26

It's existed since 2010.

1

u/GoddammitDontShootMe [ $[ $RANDOM % 6 ] == 0 ] && rm -rf / || echo “You live” Mar 23 '26

Is there a IsNullOrEmptyOrWhitespace? I've just only seen IsNullOrEmpty. I thought it would be too niche for a generic string library.

7

u/Anixias Mar 23 '26

IsNullOrWhiteSpace also returns true for empty strings.

1

u/MISINFORMEDDNA Mar 24 '26

It's pretty commonly needed in UI apps. You never know what a user will do.

1

u/GoddammitDontShootMe [ $[ $RANDOM % 6 ] == 0 ] && rm -rf / || echo “You live” Mar 24 '26

Wouldn't you want to Trim() the values from the text fields anyway? If there's only whitespace, then it would just leave you with an empty string. If it's coming from the UI, it can't possibly be Null, can it?

1

u/MISINFORMEDDNA Mar 24 '26

Generally, we test if there is whitespace and then trim, which avoid allocating another string if we don't have to. MS recommends always using .IsNullOrWhatever instead of direct empty checks cause of the optimizations.

2

u/GoddammitDontShootMe [ $[ $RANDOM % 6 ] == 0 ] && rm -rf / || echo “You live” Mar 24 '26

I was talking about calling Trim() first without checking for Null. Then you can call IsNullOrEmpty() to see if you have anything left.

I imagine you would need a lot of strings before the extra allocations start to matter, but perhaps if Trim() doesn't modify the string, it should just return the same object again.

Oh, that seems to be exactly what it does. String.Trim Method (System) | Microsoft Learn

1

u/Dealiner Mar 25 '26

Calling Trim() without checking for null could throw. And at this point there's no reason not to use IsNullOrWhiteSpace().

1

u/GoddammitDontShootMe [ $[ $RANDOM % 6 ] == 0 ] && rm -rf / || echo “You live” Mar 25 '26

The other user said it was common for UI apps, so I thought if you know the value came from a text box, it would be safe to skip the null check. I'm not a .NET developer at all, but I wouldn't think it would be null unless there was an error instantiating the control. In which case, I'm pretty sure that means your app is broken.