C
C#2y ago
Playboi17

Don’t understand nullable reference types

8 Replies
Playboi17
Playboi172y ago
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” Yet in the picture which is from a dotnet entity framework video, they just set firstname and lastname, non-nullable reference types, to null How? It says you can’t initialize to null value
Thinker
Thinker2y ago
null! essentially forces the compiler to shut up about nullability warning. You can set non-nullable reference types to null just fine, it's just the compiler which will warn you about it. But if you say "shut up" to the compiler then it won't complain
Playboi17
Playboi172y ago
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? So the “?” only affects compiler warnings and doesn’t affect the behavior of the variable?
Thinker
Thinker2y ago
For reference types, yes 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. EF will set those values for you before you can properly access them
Playboi17
Playboi172y ago
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?
Thinker
Thinker2y ago
Strings are by default null All reference types are by default null
Playboi17
Playboi172y ago
But you said “EF will set those values for you before you can properly access them”. I’m talking in that scenario.
Thinker
Thinker2y ago
I mean that when you access a model, EF with have initialized it already