开发者

Is it possible to use Variables without DIM in VB.NET?

开发者 https://www.devze.com 2023-03-19 17:55 出处:网络
Is it in VB.NET possible to use variables without the need of use DIM? now I have to use the variables like this:

Is it in VB.NET possible to use variables without the need of use DIM?

now I have to use the variables like this:

dim a = 100
dim b = 50
dim c = a + b

I want to be able to use vars in this way:

a=100
b=50
c=a+b  'c contains 150

I 开发者_运维百科think in VB6 and older VB this was possible, but I am not sure.


As far as what @Konrad said, he is correct. The answer, buried in all his caveat emptors, is the answer of "yes", you can absolutely do this in VB.NET by declaring Option Explicit Off. That said, when you do a=1, the variable a is NOT an Integer - it is an Object type. So, you can't then do c = a + b without compiler errors. You'll need to also declare Option Strict Off. And at that point, you throw away all the benefits of a compiler. Don't do it.

As an alternative, with Option Infer On, Dim behaves the same as C#'s var keyword and gives you a lot of advantages if you're trying to save on typing.


You have a fundamental misunderstanding of how VB is supposed to work. The Dim statements are there to help you. Your wish to elide them is misplaced.

The compiler enforces variable declaration so that it can warn you when you have accidentally misspelt a variable name, thus inadvertently creating a new variable, and is required to enforce type safety. Without variable declaration, VB code becomes an unreadable, unmaintainable mess.

Incidentally, the same was true in VB6, and you should have used Option Explicit in VB6 to make the compiler force you to use them properly. This option still exists in VB.NET but switching it off has no advantage, and a whole lot of disadvantages so don’t do it – instead, learn to appreciate explicit variable declarations, and all the help that the compiler is giving you through them.

0

精彩评论

暂无评论...
验证码 换一张
取 消