25

is there a way to use shorthand to do something like this?

If Not txtBookTitle.Text = String.Empty Then
  objBook.DisplayName = txtBookTitle.Text
End If
Victor Zakharov
  • 25,801
  • 18
  • 85
  • 151
SkyeBoniwell
  • 6,345
  • 12
  • 81
  • 185

4 Answers4

41
objBook.DisplayName = If(Not (txtBookTitle.Text = String.Empty), txtBookTitle.Text, objBook.DisplayName)
Mike Corcoran
  • 14,072
  • 4
  • 37
  • 49
7

There are two version of the if statement shorthand. Either If(expression, true part, false part) or If(expression, false part)

objBook.DisplayName = If(String.IsNullOrEmpty(txtBookTitle.Text), txtBookTitle.Text)
JayGee
  • 342
  • 2
  • 10
7

Following code is similar to your three line of code:

objBook.DisplayName = IIF(String.IsNullorEmpty(txtBookTitle.Text),objBook.DisplayName, txtBookTitle.Text)
Romil Kumar Jain
  • 20,239
  • 9
  • 63
  • 92
  • 4
    i dont recommend using IIF. *Both parameters WILL be evaluated* and that can produce unexpected results for example *if you use functions.* Consider this `IIF(TRUE,JustPrintOK(),ImplodeTheUniverse())`... we are doomed since both functions will be executed regardless of the condition. For VB >= 9 just use `IF` just like your example, it will work without this problem. – Sharky Mar 13 '14 at 07:21
  • 1
    Exactly, one should use `If` and `AndAlso` / `OrElse` instead – specializt Aug 22 '15 at 09:29
5

This is the shortest version (81 character):

If txtBookTitle.Text <> String.Empty Then objBook.DisplayName = txtBookTitle.Text

And I would prefer this for debug-ability. Also easily convertible to C#.

Victor Zakharov
  • 25,801
  • 18
  • 85
  • 151