i try to use this, but it doesn't work, for example:
why that code is error? can somebody explain this?Code:Public Class Form1
Dim num1 As Integer
num1 = 0
End Class
Printable View
i try to use this, but it doesn't work, for example:
why that code is error? can somebody explain this?Code:Public Class Form1
Dim num1 As Integer
num1 = 0
End Class
You can't change values of variables outside of subs.
this works:
If you want to change the value after you have declared it, you need to do that inside a subCode:Public Class Form1
Dim num1 As Integer = 0
End Class
why i can't assign the value after i declare it and why it can only be initialized? is it for avoid the variable changed outside the subroutine (that would probably make some errors?)
Because that's what the authors decided. Given that, even if you could perform a separate assignment, it could only be to a variable that you had just declared anyway, why is it a problem to combine the two? Basically, every line directly in the body of a type has to be a declaration. It can be the declaration of another type, a variable, a property, a method or whatever, but it must be a declaration. If you want to execute code other than as part of a declaration then do it in the type constructor or, if it's a form, in the Load event handler.
If you want to assign a value immediately after you have declared the variable why don't you just assign a default value when you declare it.
If you need to change it again at any point after this then this would only logically be done in a routine, like Erik said.Code:Dim myNumber As Integer = 0
Hope this helps out,
Jenova