Warning and how to optimize code

A

Aaron

Hello all,

I have 5 warnings only but I want to know how to "optimize" my code so that
it is "clean."

The warning is this with all 5 the same
Warning 1 Variable 'strxxx' is used before it has been assigned a value. A
null reference exception could result at runtime.

Here is the code

Dim strxxxAs String

.....

.....

If ckxxx.Checked = True Then

strxxx = ckxxx.Text

End If

....

.....

objMail.Body = ....

strxxx& vbCrLf + _



The warnings are in the objMail.Body part of the code.



TIA

Aaron
 
D

Damien

Aaron said:
Hello all,

I have 5 warnings only but I want to know how to "optimize" my code so that
it is "clean."

The warning is this with all 5 the same
Warning 1 Variable 'strxxx' is used before it has been assigned a value. A
null reference exception could result at runtime.

Here is the code

Dim strxxxAs String

....

....

If ckxxx.Checked = True Then

strxxx = ckxxx.Text

End If

...

....

objMail.Body = ....

strxxx& vbCrLf + _



The warnings are in the objMail.Body part of the code.
Well, what if ckxxx.Checked is false? strxxx is equal to Nothing at
this point, and that's what the compiler is warning you about. What
should the string be if ckxxx is false? An empty string? Then assign it
as such. You can do this in your Dim statement, as:

Dim strxxx as String = ""

or

Dim strxxx as String = String.Empty

or you could assign it later:

If ckxxx.Checked Then 'Note - why compare it to True?
strxxx = ckxxx.Text
Else
strxxx = ""
End If

So, in summary, there's plenty of ways to do this. Are you
concatenating lots of options together in your objMail.Body line? If
so, you might want to add the vbCrLf during the assignment to strxxx,
rather than during concatenation. Otherwise (say, for instance, there
are 6 options, and options 2 and 5 are selected), your body will be:

-----(Start of Body)

Option 2


Option 5

-----(End of Body)

Whereas if you only add the CR/LF to the string if it contains
something, you'll get:

-----(Start of Body)
Option 2
Option 5
-----(End of Body)

Hope this has helped,

Damien
 
G

Guest

Dear Aaron
It should change the following code to
Dim strxxxAs String
to
Dim strxxxAs String = ""

Since you need to pre-define the variable once you declare it

Hope this help you

Regards,
Joe Tsui
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top