'excluding null value whilst declaring variable as var

I've been away from C# since version 7.0 and been dabbling in F#.

I want to write some code and (like F#) try to exclude null, so I'm interested in the nullable capabilities of C# post 8.0, but I don't understand how to use 'var' yet declare something as non nullable

IEnumerable<int> ys = Enumerable.Range(1,10);
ys = null; // error converting null value to non null

this, is clearly invalid, as I've explicitly excluded null - brilliant, this is what I want to do almost always.

but if I write this

var ys = Enumerable.Range(1,10);
ys = null;

this IS allowed. (I was sort of expecting var? to allow nullable and var to not)

how do i use var (i.e. allow type inference) but disallow null values?



Solution 1:[1]

If you're using a newer version of C#, put the following at the top of your code:

#nullable enable

This will cause you to get warnings when something could be null that shouldn't be. However, it is a warning and not an error.

Also, if you are that concerned about the types, you may want to avoid using var and explicitly write the type you want. This will give you the most control.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jonathan Wood