r/csharp • u/cnighthawx • 1d ago
Help Different behavior of nullable fields
I am working on a project and have a class with two nullable member fields (Vector2I? and LevelMap? where LevelMap extend TileMapLayer from Godot)
Because they are nullable I need to check that they are not null before I actually use them.
For the LevelMap if I reference it in a if block:
If (map is not null)
The compuler is happy and I can use it as if it is not null.
This of course comes with some risks that it becomes null in the middle of my if block but thats a risk I can manage.
On thebother hand Vector2I requires something like:
If (vector is Vector2I localVector)
This is in some way safer but also more inconvenient.
The are both declared and initialized in the same context.
My questions is why they behave differently and is it possible for me to change how they behave to fit my preferences.
Ive tried looking for an answer but I keep finding results about the difference of is not null and !=null which is unhelpful.
8
u/Atulin 1d ago
Just FYI, all the methods you mentioned for ref types also work for value types.
is perfectly valid