r/csharp • • Aug 18 '22

Nullable Reference Migration – How to decide the nullability ?

https://thecodeblogger.com/2022/08/16/nullable-reference-migration-how-to-decide-the-nullability/
33 Upvotes

30 comments sorted by

View all comments

3

u/yanitrix Aug 18 '22

prop string Name { get; set; } = null! is the type of shit I hate with passion. You look at the entity and wonder "Did anyone set the Name or not? Am I gonna get an NRE or not?" IMO null forgiving operator should only be enabled in if (entity is not null) blocks, othwerwise it should produce error/warning. Hopefully c# 11's required props will fix it, but for now, please pass the value in constructor, you're gonna avoid this shit.

0

u/[deleted] Aug 18 '22

[removed] — view removed comment

1

u/chrisxfire Aug 18 '22

is that done by using string.Empty as a default value in the property definition?

0

u/[deleted] Aug 18 '22

[removed] — view removed comment

2

u/detroitmatt Aug 18 '22

I really don't like "store null as empty" as a design pattern because then empty just becomes the new null. it doesn't crash your program, but it still produces bugs in the form of logic errors which you have to do checks like if(m_CommandText != "") at which point you may as well have done a null check instead.