|
-
Nov 30th, 2006, 07:27 AM
#1
Thread Starter
Member
[RESOLVED] Variable used before it has been assigned a value
I have a general question about object declaration and initial instantiation. I regularly need to declare an object and then pass it byref / instantiate it in a Try Catch block. VS2005 always gives a warning:
Variable '<object name>' is used before it has been assigned a value. A null reference exception could result at runtime.
My question is do I ignore these warnings / can I explicitly switch them off / should I instead be declaring all objects used in this way like this:
VB Code:
Dim obj as Object = Nothing
This gets rid of the warning messages but is the correct way to do things and does it carry a performance penalty?
Thanks in advance for your comments.
-
Nov 30th, 2006, 08:48 AM
#2
Re: Variable used before it has been assigned a value
As you said, it's just a warning. It is up to you to determine whether it could cause problems later. At least you are aware of the possibilities in case you need to debug later. However, you can turn this feature off if you want to.
-
Dec 1st, 2006, 03:43 AM
#3
Thread Starter
Member
Re: Variable used before it has been assigned a value
Thanks for your response. Guess I was really after a best practice. Is there any difference between this: and this
VB Code:
Dim obj as Object = Nothing
and should you use the latter to suppress the warning messages or simply switch them off. Switching them off could mean that you miss a useful warning in situations where you should have initialised the object, but forgot to do so.
-
Dec 1st, 2006, 03:58 AM
#4
Re: Variable used before it has been assigned a value
You shouldn't leave any warnings in a final Release. By explicitly assigning Nothing to the variable you are telling the compiler, and anyone else who may look at the code, that you know and specifically intend for the variable to be a null reference and it wasn't just an oversight. It is good practice to initialise all variables.
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
|