|
-
Oct 20th, 2012, 04:16 AM
#1
Thread Starter
Lively Member
declare and assign variables
i try to use this, but it doesn't work, for example:
Code:
Public Class Form1
Dim num1 As Integer
num1 = 0
End Class
why that code is error? can somebody explain this?
-
Oct 20th, 2012, 04:22 AM
#2
Member
Re: declare and assign variables
You can't change values of variables outside of subs.
this works:
Code:
Public Class Form1
Dim num1 As Integer = 0
End Class
If you want to change the value after you have declared it, you need to do that inside a sub
-
Oct 20th, 2012, 08:24 AM
#3
Thread Starter
Lively Member
Re: declare and assign variables
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?)
-
Oct 20th, 2012, 08:45 AM
#4
Re: declare and assign variables
 Originally Posted by chipp
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.
-
Oct 20th, 2012, 08:46 AM
#5
Re: declare and assign variables
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.
Code:
Dim myNumber As Integer = 0
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.
Hope this helps out,
Jenova
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|