why dont nullable strings have a hasValue() method?

Viewed 4519

I have a class which contains a nullable strings, I want to make a check to see whether they stay null or somebody has set them.

simliar to strings, the class contains integers which are nullable, where i can perform this check by doing an equality comparison with the .HasValue() method - it seems like strings dont have this?

So how do check whether it goes from null to notNull?

public class Test 
{
    public string? a
    public string? b
    public int? c
} 

var oldQ = new Test(c=123)
var newQ = new Test(c=546)

bool isStilValid = newQ.c.HasValue() == oldQ.c.HasValue() //(this is not possible?)&& newQ.b.HasValue() == oldQ.b.HasValue()

why is this not possible?

3 Answers

HasValue property belongs to Nullable<T> struct, where T is also restricted to be a value type only. So, HasValue is exist only for value types.

Nullable reference types are implemented using type annotations, you can't use the same approach with nullable value types. To check a reference type for nullability you could use comparison with null or IsNullOrEmpty method (for strings only). So, you can rewrite your code a little bit

var oldQ = new Test() { c = 123 };
var newQ = new Test() { c = 456 };

bool isStilValid = string.IsNullOrEmpty(newQ.b) == string.IsNullOrEmpty(oldQ.b);

Or just use a regular comparison with null

bool isStilValid = (newQ.b != null) == (oldQ.b != null);

The equivalent comparing to null would be:

bool isStillValid = (newQ.c != null) == (oldQ.c != null) && (newQ.b != null) == (oldQ.b != null);

That's the equivalent to your original code, but I'm not sure the original code is correct...

isStillValid will be true if ALL the items being tested for null are actually null. Is that really what you intended?

That is, if newQ.c is null and oldQ.c is null and newQ.b is null and oldQ.b is null then isStillValid will be true.

The Nullable<T> type requires a type T that is a non-nullable value type for example int or double. string typed variables are already null, so the nullable string typed variable doesn't make sense.

You need to use string.IsNullOrEmpty or simply null

Related