Bohn
Bohn

Reputation: 26919

Why am I able to assign an integer to a string in VB.NET

I have worked with C#.NET and this is the first time have to write VB.NET code. So I wrote this, it compiled successfully.

Sub Main()

    Dim x As String
    x = 23

End Sub

Shouldn't I get a compile error?

Upvotes: 1

Views: 64

Answers (2)

Adam Silenko
Adam Silenko

Reputation: 3108

Because you allow Implicit Conversions probably in Compiler Configuration Options by setting Option Strict to off.
You can change it in: Properties of Project > Compile tab > Option Strict.
Alternatively add Option Strict, at the top of the source code file, to require explicit declaration of variables.
PS corrected, thanks @BlueMonkMN for your notice.

Upvotes: 1

BlueMonkMN
BlueMonkMN

Reputation: 25601

Option Strict: Restricts implicit data type conversions to only widening conversions, disallows late binding, and disallows implicit typing that results in an Object type.

It can be set at the project level: enter image description here

Or at the file level by putting a line at the beginning like:

Option Strict On

or

Option Strict Off

Upvotes: 3

Related Questions