23

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
  • 24,856
  • 17
  • 77
  • 143
SkyeBoniwell
  • 5,795
  • 11
  • 71
  • 148

4 Answers4

38
objBook.DisplayName = If(Not (txtBookTitle.Text = String.Empty), txtBookTitle.Text, objBook.DisplayName)
Mike Corcoran
  • 13,382
  • 4
  • 33
  • 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
5

Following code is similar to your three line of code:

objBook.DisplayName = IIF(String.IsNullorEmpty(txtBookTitle.Text),objBook.DisplayName, txtBookTitle.Text)
Romil Kumar Jain
  • 19,561
  • 8
  • 59
  • 90
  • 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
  • 24,856
  • 17
  • 77
  • 143