C# has String.IsNullOrWhiteSpace(String), do we have a IsNothingOrWhiteSpace(String)?
Does a method exist to check if a variable is Nothing or WhiteSpace?
143 Views Asked by AudioBubble At
2
There are 2 best solutions below
0
On
I've searched the documentation and it doesn't seem to exist, but you can write it yourself.
function IsNullOrWhiteSpace(verify::Any)
# If verify is nothing, then the left side will return true.
# If verify is Nothing, then the right side will be true.
return isnothing(verify) || isa(nothing,verify)
end
function IsNullOrWhiteSpace(verify::AbstractString)
return isempty(strip(verify))
end
println(IsNullOrWhiteSpace(nothing)) # true
println(IsNullOrWhiteSpace(" ")) # true
Might not be the best way to do it, but it works.
Why do we need both isnothing() and isa()?
Let's see what will happen when we use isnothing() with nothing and Nothing.
println(isnothing(nothing)) # true
println(isnothing(Nothing)) # false
We obviously want to handle Nothing, how do we do it?
Using isa(), it will test if nothing is a type of Nothing.
A slightly more elegant way than the other answer would be to fully use the multiple dispatch:
This actually results also in a faster assembly code.