Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why dont nullable strings have a hasValue() method?

Tags:

c#

nullable

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?

like image 580
kafka Avatar asked Feb 11 '26 14:02

kafka


2 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);
like image 58
Pavel Anikhouski Avatar answered Feb 14 '26 03:02

Pavel Anikhouski


Only struct in C# have HasValue method, but you can simple create your own string extension as below and that will solve your problem.

public static class StringExtension {

    public static bool HasValue(this string value)
    {
        return !string.IsNullOrEmpty(value);
    }
}

I hope this is helpful for someone.

like image 38
Carlos Gregorio Avatar answered Feb 14 '26 04:02

Carlos Gregorio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!