{String1 = Nothing or "Blahblah"} ... String1 should = "Blahblah" not exception?

JBlue

New member
Joined
Aug 18, 2013
Messages
3
Programming Experience
1-3
{String1 = Nothing or "Blahblah"} ... String1 should = "Blahblah" not exception?

Hi everyone, I'm brand new here, sorry about the title but it was the best way I could summarise my problem.

My code scenario is this:


VB.NET:
Dim String1 as String
Dim PotentialNullString as String = Nothing



String1 = PotentialNullString Or "This is an Empty String"

Now this code returns a null reference exception. What I want is a way to get String1 to get the value of PotentialNullString but if that happens to be Nothing then it should be "This is an Empty String".

I know this is quite easily doable by checking If PotentialNullString IsNot Nothing first but I want to do it all on one line, one expression.

Is this possible?
 
If Operator (Visual Basic) see "If Operator Called with Two Arguments"
        Dim PotentialNullString As String = Nothing

        Dim String1 = If(PotentialNullString, "This is an Empty String")
 
Ah thanks for the reply JohnH. I had tried the If operator with two arguments and it didn't work and on double checking I noticed it works in this scenario but my actual scenario was a little more complicated. It involved a Null object reference as opposed to just an empty string. This problem happens when the string is from another object. I'll try explain this better this time:

VB.NET:
Public Class Book
Public Title as String
End Class

Public Sub TheProblem()

Dim String1 as String
Dim NullBook as Book = Nothing

String1 = If(Book.Title, "Invalid Book") 'This line causes a nullreference exception
End Sub
Because Book doesn't exist its faulting on getting the title value, but in principal shouldn't it work in the same manner as you suggested to me?
 
You mean NullBook.Title, not Book.Title. No, there would have to be a Book object for that to work, accessing the Title property on a null reference throws that exception.
You have to use the If operator with three arguments, checking for object before using it:
Dim String1 = If(NullBook IsNot Nothing, NullBook.Title, "Invalid Book")

This would still not have the exact same meaning, because the Title can be Nothing also.
 
Perfect, this is exactly what I was looking for. I didn't realise I could use more than 2 arguments for If().!
So you didn't read the article I linked to? It was for you I posted it.
 
Back
Top