Question Why type conversion not needed? Please provide information.

marksquall

Active member
Joined
Oct 17, 2009
Messages
28
Programming Experience
3-5
Dear vbdotnetforums.com administrators and members,

A greeting of peace. I hope everyone is in good health upon reading this forum.

I am just a little shocked with this VB .NET console application I just wrote:

VB.NET:
Module MyModule
  Sub Main()
      Dim num As Integer
      Dim square As Integer
      Console.Write("Please enter your grade: ")
      num = Console.ReadLine()
      square = num * num
      Console.WriteLine("The square of " & num & " is " & square)
  End Sub
End Module

My question is that why VB .NET "accepted" line 5? According to MSDN , the ReadLine() method returns a String. Is there any information I could read why VB .NET allowed this? I get used to Java that you need to parse String to a certian data type. But on my program, it seems like an autocasting to me.

I hope to hear from you guys who might know why this is allowed. Thank you very much.


Warm regards,

MarkSquall
 
Last edited:
Your num variable is declared as type Integer. When you assign this a value of type String an implicit conversion occurs. This code will not compile if you turn on Option Strict, which I recommend you do because you get much better help from compiler relating to type conversions and assignments and also better help from intellisense, in addition to making you a better and more aware developer.
Option Strict is off by default because MS thinks this makes VB.Net more accessible to beginners, but that is debatable. The IDE and language has evolved so much over the years that now it is more helpful to develop with a stricter syntax.
 
New knowledge acquired. Thanks Sir JohnH.

Dear Sir JohnH,

Thank you so much for the new knowledge you shared to me Sir. I am not really familiar what Option Strict actually do in VB, but now I do. I will put this on every code I will make.

Again, thank you very much Sir JohnH.

Warm regards,

MarkSquall
 
There's a setting for Option Strict in Compile tab of Project properties.
You can also set default for new projects in Options > Project and Solutions > VB Defaults.
In addition you may override the setting in individual code files using the Option Strict statement at top of page.
 
Dear Sir JohnH,

Hello Sir. What a quick response...anyway, to be honest Sir, I am using plain notepad and command-line vbc.exe in making console programs in VB .NET. But your suggestion will greatly help "configure" my Visual Studio .NET 2003. I turn my Option Strict on. But is there such settings in Visual Studio .NET 2003 where in which there is already an Option Strict code (just above Module Module1 code) every time I create a new Console Apllication Project in VB .NET.

Thanks again Sir.

Warm regards,


MarkSquall
 

Latest posts

Back
Top