|
-
Sep 17th, 2007, 07:41 PM
#1
Thread Starter
Lively Member
VB Warning
Hey Everyone
I use variable throughout my program that i just converted from vb6.0. i'm getting this warning. The code is below. Any ideas on improving my coding
Thanks
Code:
Dim lblEXH As Label
Dim lblBBCD As Label
Dim lblCDLE As Label
Dim txtSE As TextBox
Dim txtDCP As TextBox
txtIBR.Text = ""
txtIA.Text = ""
txtDCP.Text = " "
txtSE.Text = ""
lblCDLE.Text = ""
lblBBCD.Text = ""
lblEXH.Text = ""
txtIA.Focus()
Warning 1
Variable 'DDD' is used before it has been assigned a value.
A null reference exception could result at runtime.
-
Sep 17th, 2007, 07:55 PM
#2
Re: VB Warning
Well, there's no DDD variable declared in that code for a start, so we can't speak to that variable specifically. You get that warning when you declare a reference type variable, i.e. a class, and then use it before assigning an object to it. It is quite possible that a NullReferenceException will result at run time if you have not taken steps to avoid it. The warning is there in case you simply forgot to assign an object to the variable. If you know for a fact that an exception will not result and you specifically intended for nothing to be assigned to the variable, then you can clear the warning by telling the compiler exactly that, e.g.
vb.net Code:
Dim var As Object = Nothing
By explicitly assigning Nothing to the variable you're telling the compiler that you know it's nothing and you want it to be nothing, so the compiler assumes that you will have taken the required steps to ensure an exception does not result.
-
Sep 17th, 2007, 08:03 PM
#3
Thread Starter
Lively Member
Re: VB Warning
This is a beter example.
Code:
as2 = 180 / 3.14159
Dim DD As Double
'X = 0.021585
'asin (x)= Atn(x / Sqr(1 - x ^ 2))
DD = System.Math.Atan(X / System.Math.Sqrt(1 - X ^ 2)) * 180 / 3.14159
-
Sep 17th, 2007, 09:04 PM
#4
Re: VB Warning
No, that's not an example at all because in that code DD is not a reference type. A value type can never be a null reference so no warning will be given. THIS is a better example:
vb.net Code:
Dim o As Object
Me.SomeMethod(o)
The second line will cause that warning message to be displayed. It is telling you that no object has been assigned to the variable 'o' so if you try to access its members inside the method a NullReferenceException will result. I've already told you what to do about it:
vb.net Code:
Dim o As Object = Nothing
Me.SomeMethod(o)
If you specifically want the variable to refer to Nothing then explicitly state that. This will not stop any NullReferenceExceptions being thrown if you still don't use the variable properly, but it tells the compiler that you haven't just forgotten to assign a value so it will not display the warning.
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
|