views:

59

answers:

2

I've got an IF statement that validates data.

Basically looks like this:

Dim s As String = Nothing

If s Is Nothing Or s.Length = 0 Then
    Console.WriteLine("Please enter a value")
End If

Console.Read()

I'd like to check to see if it's nothing first because if I write it this way, it throws a NullReferenceException.

I've thought of re-writing it like this:

If s Is Nothing Then
    Console.WriteLine("Please enter a value")
ElseIf s.Length = 0 Then
    Console.WriteLine("Please enter a value")
End If

But if I do this I've got the same error message twice and I believe it's less clear what my intent is.

I've also tried throwing parenthesis around the s Is Nothing clause, but it doesn't work.

Is there an elegant what to test if the object is nothing and then test a property of it?

+7  A: 

.NET 2.0 introduced the OrElse keyword to do short-circuiting. What this means is that it will not evaluate the right-side of the OrElse if the left side is true. Other than that, it works exactly like Or.

The And equivalent is AndAlso, which will not evaluate the right side if the left side is false.

Dim s As String = Nothing

If s Is Nothing OrElse s.Length = 0 Then
    Console.WriteLine("Please enter a value")
End If

Console.Read()

should do what you want.

R. Bemrose
True. However, this does not explain why his second code also throws a NullReference exception. In the ignorance of this keyword, his second code should be a valid workaround.
Daniel Daranas
@Daniel Daranas: Hmm, that is true. I guess I just can't wrap my head around Is Nothing returning a NullReferenceException.
R. Bemrose
Oops I think I misunderstood what the OP said. He says he "gets the same error message twice", probably refering to "Please enter a value".
Daniel Daranas
Sorry if I was unclear, what I meant was that I get the NullReference only in the first example. In the second example I have to include the error message ("Please enter a value") twice, hence violating DRY.
Nathan Koop
@Nathan I understood, after a second reading. However, you could easily manage that by setting a boolean variable "isInputInvalid" to true and then check it and show the message if it is true.
Daniel Daranas
@Daniel Daranas: You're right but OrElse is even better/more simple ;)
Meta-Knight
ShellShock
+4  A: 

you can use:

if (string.IsNullOrEmpty(s))
{
//do work
}
CSharpAtl
I didn't think of that one. Good catch.
R. Bemrose
yeah it is a nice method that makes the code look cleaner...and of course is only going to work for string....
CSharpAtl
@CSharpAtl: True, but it expresses the intent more clearly, and checks if it's String.Empty to boot.
R. Bemrose
Thanks, this works but my example was a simplification of a more complex object.
Nathan Koop
Yeah I threw this in because it works for your specific example.....but will not work on a generic object sense...
CSharpAtl