Groups | Blog | Home
all groups > asp.net > january 2006 >

asp.net : Warning and how to optimize code



Aaron
1/18/2006 11:56:33 PM
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

Damien
1/19/2006 12:00:27 AM
[quoted text, click to view]
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
Joe
1/19/2006 12:02:02 AM
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




[quoted text, click to view]
AddThis Social Bookmark Button