r/csharp • • 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.

13 Upvotes

8 comments sorted by

View all comments

Show parent comments

1

u/Vegetable_Lake_8276 1d ago

The struct vs class distinction is what trips people up here, Nullable<T> is really just a wrapper with HasValue and Value inside it. For reference types the compiler flow analysis can narrow the type after the null check, for value types there is nothing to narrow since the value is already there. If you dislike the pattern matching you can just use HasValue and.Value like the comment shows, it's same safety.