C
Join ServerC#
help
Don’t understand nullable reference types
PPlayboi1710/19/2022


PPlayboi1710/19/2022
Documentation says that non-nullable reference types “must be initialized to a non-null value” and “compiler issues a warning when code assigns maybe-null”
PPlayboi1710/19/2022
Yet in the picture which is from a dotnet entity framework video, they just set firstname and lastname, non-nullable reference types, to null
PPlayboi1710/19/2022
How? It says you can’t initialize to null value
Tthinker22710/19/2022
null!
essentially forces the compiler to shut up about nullability warning.Tthinker22710/19/2022
You can set non-nullable reference types to null just fine, it's just the compiler which will warn you about it.
Tthinker22710/19/2022
But if you say "shut up" to the compiler then it won't complain
PPlayboi1710/19/2022
Thank you. I dont see why you would want to lose the warnings? If you don’t want the warnings and can still set it to null, why not use a nullable reference type?
PPlayboi1710/19/2022
So the “?” only affects compiler warnings and doesn’t affect the behavior of the variable?
Tthinker22710/19/2022
For reference types, yes
Tthinker22710/19/2022
Sometimes you have a situation (like with EF) where you don't have an initial value to set anything to, but you know for certain that the value won't be null when you actually access it.
Tthinker22710/19/2022
EF will set those values for you before you can properly access them
PPlayboi1710/19/2022
Answered before I could ask, are you saying it has a default constructor? If you don’t initialize firstname for example, will it just make it white space?
Tthinker22710/19/2022
Strings are by default null
Tthinker22710/19/2022
All reference types are by default null
PPlayboi1710/19/2022
But you said “EF will set those values for you before you can properly access them”. I’m talking in that scenario.
Tthinker22710/19/2022
I mean that when you access a model, EF with have initialized it already