Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format number with leading zeroes in .NET 2.0

Tags:

vb.net

I have problem to format numbers and convert it to string with leading zeroes when application uses NET framework 2.0 with Visual Basic.

I try:

Dim myNum = 12
Dim myStr as String

Dim myStr = myNum.ToString("0000")
or
Dim myStr = myNum.ToString("D4") 

... in order to get wanted string: 0012

Please help to solve this.

like image 665
Wine Too Avatar asked Oct 27 '25 03:10

Wine Too


1 Answers

You have an old version of Visual Studio, one that doesn't have Option Infer yet. Or it isn't turned on. That makes the myNum identifier a variable of type Object.

So your code tries to call the Object.ToString() method. Which does not have an overload that takes an argument. The compiler now tries to make hay of your code and can only do so by treating ("0000") or ("D4") as an array index expression. Indexing the string that's returned by Object.ToString(). That has pretty funny side effects, to put it mildly. A string like "0000" is not a valid index expression, the compiler generates code to automatically convert it to an Integer. That works for "0000", converted to 0 and the result is a character, just "1"c. Converting "D4" to an integer does not work so well of course, that's a loud Kaboom!

The solution is a very simple one, just name the type of the variable explicitly:

  Dim myNum As Integer = 12
  Dim myStr = myNum.ToString("D4")    '' Fine

VB.NET's support for dynamic typing is pretty in/famous. Meant to help new programmers getting started, it in fact is an advanced technique given the myriad ways it can behave in very unexpected ways.

The universal advice is always the same. Let the compiler help you catch mistakes like this. Put this at the top of your source code file:

 Option Strict On
like image 109
Hans Passant Avatar answered Oct 29 '25 04:10

Hans Passant