Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null safe string

Tags:

c#

.net-core

I have a localzation string which apparently if set to null is causing issues in the view. So my solution was to string it.

_localizer["Controller_Account_ResetPassword_ResetFailed"].ToString();

During code review my co-worker reminded me that .ToString() is not null safe. While its highly unlikely that a localization would be null I guess it could be. He suggested the following.

TempData["Message"] = $"{_localizer["Controller_Account_ResetPassword_ResetFailed"]}";

I have two questions.

  1. Why is $"{var}" null safe and .ToString() is not.
  2. Is there a better way of doing it because his solution seams ugly to me.
like image 599
DaImTo Avatar asked Aug 20 '26 20:08

DaImTo


1 Answers

First of all, the reason is that it's basically decompiled as

var arg = _localizer["Controller_Account_ResetPassword_ResetFailed"];
string.Format("{0}", arg);

and string.Format does a null check on its arguments and automatically replaces them with string.Empty.

Second of all, this solution is beautiful and string interpolation is an ingenious tool. You should use it :)

EDIT:

I kinda overlooked the fact here string interpolation is used solely to fix the null problem. As some have pointed out that is unnecessary and as much as everyone should love string interpolation something like this:

_localizer["Controller_Account_ResetPassword_ResetFailed"]?.ToString() ?? "";

would be a better choice.

like image 153
V0ldek Avatar answered Aug 22 '26 11:08

V0ldek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!