7

Option Strict was off in my VB app so I have now turned it on. I now have some errors that I am unsure on how to fix:

pnlWait.Top = (Height - pnlWait.Height) / 2

In C# I would just do:

pnlWait.Top = (int)(Height - pnlWait.Height) / 2;

But this doesn't work in VB. I tried Decimal.ToInt32 but then it complains because it is creating a Double with the division and there is no Double.ToInt32. Interger.Parse requires a String, so this can't be any good.

pnlWait.Top = Integer.Parse(((Height - pnlWait.Height) / 2).ToString) 'Yeah, right!

That makes me think CType or DirectCast may be good, but these methods work on many objects so I don't think they could be efficient.

Bugs
  • 4,491
  • 9
  • 32
  • 41
John
  • 267
  • 1
  • 3
  • 12
  • 1
    I always use Convert.ToInt32([double]) – soohoonigan Nov 07 '16 at 22:36
  • 5
    for that *particular* code you can use integer division: `pnlWait.Top = (Height - pnlWait.Height) \ 2` – Ňɏssa Pøngjǣrdenlarp Nov 07 '16 at 22:43
  • 1
    The reference material [Type Conversion Functions (Visual Basic)](https://msdn.microsoft.com/en-us/library/s2dy91zy.aspx?f=255&MSPPError=-2147217396) recommends using the language implemented conversion operators and leaving it to the compiler to select a conversion method. I am somewhat ambivalent about what constitutes the best conversion method. Some methods involve rounding that you should be aware of and others may follow a call chain that affects performance, My advise is to know the tools you use; i.e. RTFM. :) – TnTinMn Nov 08 '16 at 02:12
  • or bit shift `pnlWait.Top = (Height - pnlWait.Height) >> 1` for micro optimization and to confuse anyone looking at the code :] – Slai Nov 23 '16 at 17:20

2 Answers2

1
pnlWait.Top = Convert.ToInt32((Me.Height - pnlWait.Height) / 2)
Guru Josh
  • 566
  • 8
  • 16
1

After going over the link tinman posted I believe the best choice is to use the VB.Net specific conversion functions. I initially avoided them thinking they were hold overs from VB but it seems they are not. I was sold when it mentioned that they are compiled inline, so I will use CInt and the others.

Except in my example, I will use the suggestion offered by Plutonix. I completely forgot about that one.

So generally I will use

pnlWait.Top = CInt((Height - pnlWait.Height) / 2)

And

If DR.Item(Mailings.WelcomePacket.SelectToMail) Then

Becomes

If CBool(DR.Item(Mailings.WelcomePacket.SelectToMail)) Then

Except

pnlWait.Top = (Height - pnlWait.Height) \ 2

is much cleaner.

John
  • 267
  • 1
  • 3
  • 12
  • I would use the last version with the integer division. `(int)` rounds towards 0, but `CInt` rounds towards even http://stackoverflow.com/questions/4181942/convert-double-to-int/4181954#comment68670590_4181954 so `3 \ 2` is 1, but `CInt(1.5)` is 2. Also, `CBool(object)` trows Exception if conversion to Boolean fails (for example `DBNull.Value`), so I would recommend `object.Equals(True)` or `True.Equals(object)` – Slai Nov 23 '16 at 17:05