Be Kind To New Users
Be Kind To New Users

Reputation: 10073

Variable declaration without an 'As' clause

I have code that looks like this:

Private Shared Function Dec2Base(ByVal DecNum, ByVal Base) As String
    Dim NHD As Double
    Dim HN As String = ""

    While DecNum <> 0
        NHD = DecNum - (Int(DecNum / Base) * Base)
        HN = Mid("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", NHD + 1, 1) & HN
        DecNum = Int(DecNum / Base)
    End While

    Dec2Base = HN
End Function

It is causing this compile error:

Variable declaration without an 'As' clause; type of Object assumed.

So I looked at the code and concluded that DecNum and Base where Integers and added the As Integer to the function declaration.

Then I stumbled on this call:

Public Shared Function SetP() As String
    Dim b = Format(Now(), "MMddyy")

    SetP = Dec2Base(b, 17)

End Function

And several like it. That is: DecNum is being passed in as a String.

What is the proper way to eliminate the compile warning message?

  1. ByVal DecNum As String?
  2. ByVal DecNum As Integer?
  3. Something else?

Exactly when is the type conversions happening in the existing code and how will that be changed by adding the As clause?

Upvotes: 0

Views: 823

Answers (2)

tinstaafl
tinstaafl

Reputation: 6958

I would say that DecNum and Base should most probably be Integers.

A few things I noticed:

Instead of using a string literal it would be better to use a Const variable. This gives you the option of using string indexing instead of the Mid function. The index will simply be the modulus of the number divided by the base.

One shortcut that vb.net has is a special Integer Division sign(\). If you want the result of a division to be an integer you can use this sign and the casting is done automatically.

With these in mind your code could look something like this:

Private Function Dec2Base2(ByVal DecNum As Integer, ByVal Base As Integer) As String
    Const DIGITS As String = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    Dim s As String = ""
    Dim num = DecNum
    While num > 0
        s = DIGITS(num Mod Base) & s
        num = num \ Base
    End While
    Return s
End Function

Upvotes: 2

MWS
MWS

Reputation: 78

To eliminate the warning you can just use ByVal DecNum as Object but the behaviour may be undefined since it will implicitly convert it to a string or integer based on what was passed in. I would probably use the Integer type and re-write any calls to pass that in as the type.

Upvotes: 1

Related Questions