Aaron wrote:
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