473,467 Members | 1,998 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

VS2005: Code "gramatically" correct..

Hi all,

Ok - I've used the word gramatically - which I'm sure is incorect, however I
mean when VS2005 lists "warnings" like this one:

Warning 1 Variable 'Command' is used before it has been assigned a value. A
null reference exception could result at runtime.
Warning 2 Variable 'Connection' is used before it has been assigned a value.
A null reference exception could result at runtime.
Warning 3 Variable 'Command' is used before it has been assigned a value. A
null reference exception could result at runtime.
Warning 4 Variable 'Connection' is used before it has been assigned a value.
A null reference exception could result at runtime.

Now, in my code I often do this within the "catch" part of a try..catch if
I've used a database connection/command in the "Try" section;

' tidy up
If Command Is Nothing <> False Then
Command.Dispose()
Command = Nothing
End If

If Connection Is Nothing <> False Then
Connection.Close()
Connection = Nothing
End If

The reason I do this, I believe is for tidyness, its quite possible that if
an exception was caused I may have already created my connection object,
and/or my Command object, therefore I test to see if they are "something",
and if so deal with them appropriately..

Of course, now with its new gadgets VS reports problems because I've not
"something'd" them in the "Catch" although I have in the "Try"...

Any suggestions - is my coding bad? Is there a better way? Any info
appreciated, I'm trying to go for good coding practices you see :o)

Rob
Nov 19 '05 #1
6 1191
One comment, is that when you are testing that the result of a boolean
expression is not equal to false - that is really confusing to read. A more
readable way is:

If Command Is Nothing = True Then

And, better yet:

If Command Is Nothing Then

Which is the most readable out of all of them.

Now, in all of the cases above, your If statement will execute, which is not
what you want, since you will get a nullreferenceexception.

Which proves my point as to just how confusing writing code like that is.

Now, the compiler can only do so much in figuring out your code. It may be,
that your code is written in such a way, that an object is always assigned
before you use it. If you want to get rid of the warning, always assign the
variable, even if it is to nothing.

And lastly, you do not need to set the variables to Nothing. That was
something you had to do in VB6.

"Rob Meade" <te**************@edaem.bbor> wrote in message
news:0a***************@text.news.blueyonder.co.uk. ..
Hi all,

Ok - I've used the word gramatically - which I'm sure is incorect, however
I mean when VS2005 lists "warnings" like this one:

Warning 1 Variable 'Command' is used before it has been assigned a value.
A null reference exception could result at runtime.
Warning 2 Variable 'Connection' is used before it has been assigned a
value. A null reference exception could result at runtime.
Warning 3 Variable 'Command' is used before it has been assigned a value.
A null reference exception could result at runtime.
Warning 4 Variable 'Connection' is used before it has been assigned a
value. A null reference exception could result at runtime.

Now, in my code I often do this within the "catch" part of a try..catch if
I've used a database connection/command in the "Try" section;

' tidy up
If Command Is Nothing <> False Then
Command.Dispose()
Command = Nothing
End If

If Connection Is Nothing <> False Then
Connection.Close()
Connection = Nothing
End If

The reason I do this, I believe is for tidyness, its quite possible that
if an exception was caused I may have already created my connection
object, and/or my Command object, therefore I test to see if they are
"something", and if so deal with them appropriately..

Of course, now with its new gadgets VS reports problems because I've not
"something'd" them in the "Catch" although I have in the "Try"...

Any suggestions - is my coding bad? Is there a better way? Any info
appreciated, I'm trying to go for good coding practices you see :o)

Rob

Nov 19 '05 #2
You have a few options:

1. You can ignore warnings which you are certain are not going to cause a
problem. Not a bad idea. After all, a warning is not a show-stopper, but it
does bring your attention to a potential problem.
2. You can turn off certain types of warnings in Tools|Options.
3. You can write code that the IDE prefers you to write. Not a bad idea.
There are good reasons why these warnings are raised, and adapting good
coding practices is always a help.
4. Some combination of the above which suits your specific personality
and/or needs.

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
A watched clock never boils.

"Rob Meade" <te**************@edaem.bbor> wrote in message
news:0a***************@text.news.blueyonder.co.uk. ..
Hi all,

Ok - I've used the word gramatically - which I'm sure is incorect, however
I mean when VS2005 lists "warnings" like this one:

Warning 1 Variable 'Command' is used before it has been assigned a value.
A null reference exception could result at runtime.
Warning 2 Variable 'Connection' is used before it has been assigned a
value. A null reference exception could result at runtime.
Warning 3 Variable 'Command' is used before it has been assigned a value.
A null reference exception could result at runtime.
Warning 4 Variable 'Connection' is used before it has been assigned a
value. A null reference exception could result at runtime.

Now, in my code I often do this within the "catch" part of a try..catch if
I've used a database connection/command in the "Try" section;

' tidy up
If Command Is Nothing <> False Then
Command.Dispose()
Command = Nothing
End If

If Connection Is Nothing <> False Then
Connection.Close()
Connection = Nothing
End If

The reason I do this, I believe is for tidyness, its quite possible that
if an exception was caused I may have already created my connection
object, and/or my Command object, therefore I test to see if they are
"something", and if so deal with them appropriately..

Of course, now with its new gadgets VS reports problems because I've not
"something'd" them in the "Catch" although I have in the "Try"...

Any suggestions - is my coding bad? Is there a better way? Any info
appreciated, I'm trying to go for good coding practices you see :o)

Rob

Nov 19 '05 #3
"Marina" wrote ...
One comment, is that when you are testing that the result of a boolean
expression is not equal to false - that is really confusing to read. A
more readable way is:

If Command Is Nothing = True Then

And, better yet:

If Command Is Nothing Then
Hi Marina,

I understand what you are saying, and thank you for the reply, however, in
my example:

If Command Is Nothing <> False Then
Command.Dispose()
Command = Nothing
End If

I would then have do add more code, ie,

If Command Is Nothing Then
' do nothing
Else
Command.Dispose
Command = Nothing
End If

Easier to read - but more code...
Now, in all of the cases above, your If statement will execute, which is
not what you want, since you will get a nullreferenceexception.
But this is why I'm testing it? Am I not saying in the test, if the object
is "something" then kill it off? ie, if its "nothing" (null?) then dont
worry...skip right past...
Which proves my point as to just how confusing writing code like that is.
I'm obviously missing something, it makes sense to me - is what I've replied
with above here wrong then?
Now, the compiler can only do so much in figuring out your code. It may
be, that your code is written in such a way, that an object is always
assigned before you use it. If you want to get rid of the warning, always
assign the variable, even if it is to nothing.
The full chunk is as follows:

Public Function TruncateDatabase() As Boolean

' declare variables
Dim Connection As SqlConnection
Dim Command As SqlCommand
Dim Result As Boolean

' exception handling
Try

' create and open our database connection
Connection = New
SqlConnection(ConfigurationManager.AppSettings("We bmasters"))
Connection.Open()

' create and define our command object
Command = New SqlCommand
Command.Connection = Connection
Command.CommandType = CommandType.Text
Command.CommandText = "TRUNCATE TABLE Webmasters"

' execute
Command.ExecuteNonQuery()

' tidy up
Command.Dispose()
Command = Nothing
Connection.Close()
Connection = Nothing

' set result
Result = True

Catch ex As Exception

' TODO: Error handling

' tidy up
If Command Is Nothing <> False Then

Command.Dispose()
Command = Nothing

End If

If Connection Is Nothing <> False Then

Connection.Close()
Connection = Nothing

End If

' set flag
Result = False

End Try

' return result
Return Result

End Function

As per my initial post, I only actually set a value to those objects in the
"Try" block, hence the warning...as you suggested, setting them to nothing
at the top outside of Try would obviously clear these up.
And lastly, you do not need to set the variables to Nothing. That was
something you had to do in VB6.


I do that for completeness, I read/heard about .net clearing up after itself
as and when it deems appropriate, I just like to save it the trouble :)

Rob
Nov 19 '05 #4
"Kevin Spencer" wrote...
1. You can ignore warnings which you are certain are not going to cause a
problem. Not a bad idea. After all, a warning is not a show-stopper, but
it does bring your attention to a potential problem.
I love 'em - I think its one of my favourite things thus far between
2003/2005 - I've always been very task orientated, so for me this is dead
handy, oh look a long list of stuff to sort out :o)
2. You can turn off certain types of warnings in Tools|Options.
nah..
3. You can write code that the IDE prefers you to write. Not a bad idea.
There are good reasons why these warnings are raised, and adapting good
coding practices is always a help.
Sounds like a good idea.
4. Some combination of the above which suits your specific personality
and/or needs.


3 for me I think :o)

Cheers Kevin,

Rob
Nov 19 '05 #5
re:
I understand what you are saying, and thank you for the reply, however, in my example:

If Command Is Nothing <> False Then
Command.Dispose()
Command = Nothing
End If

I would then have do add more code, ie,
Wouldn't :

If Command Then
Command.Dispose()
Command = Nothing
End If

work better ?

In C#, that works, too :

if (Command) {
Command.Dispose();
Command = null;
}

Juan T. Llibre, ASP.NET MVP
ASP.NET FAQ : http://asp.net.do/faq/
Foros de ASP.NET en Español : http://asp.net.do/foros/
======================================
"Rob Meade" <te**************@edaem.bbor> wrote in message
news:BT**************@text.news.blueyonder.co.uk.. . "Marina" wrote ...
One comment, is that when you are testing that the result of a boolean expression is
not equal to false - that is really confusing to read. A more readable way is:

If Command Is Nothing = True Then

And, better yet:

If Command Is Nothing Then


Hi Marina,

I understand what you are saying, and thank you for the reply, however, in my example:

If Command Is Nothing <> False Then
Command.Dispose()
Command = Nothing
End If

I would then have do add more code, ie,

If Command Is Nothing Then
' do nothing
Else
Command.Dispose
Command = Nothing
End If

Easier to read - but more code...
Now, in all of the cases above, your If statement will execute, which is not what you
want, since you will get a nullreferenceexception.


But this is why I'm testing it? Am I not saying in the test, if the object is
"something" then kill it off? ie, if its "nothing" (null?) then dont worry...skip right
past...
Which proves my point as to just how confusing writing code like that is.


I'm obviously missing something, it makes sense to me - is what I've replied with above
here wrong then?
Now, the compiler can only do so much in figuring out your code. It may be, that your
code is written in such a way, that an object is always assigned before you use it. If
you want to get rid of the warning, always assign the variable, even if it is to
nothing.


The full chunk is as follows:

Public Function TruncateDatabase() As Boolean

' declare variables
Dim Connection As SqlConnection
Dim Command As SqlCommand
Dim Result As Boolean

' exception handling
Try

' create and open our database connection
Connection = New SqlConnection(ConfigurationManager.AppSettings("We bmasters"))
Connection.Open()

' create and define our command object
Command = New SqlCommand
Command.Connection = Connection
Command.CommandType = CommandType.Text
Command.CommandText = "TRUNCATE TABLE Webmasters"

' execute
Command.ExecuteNonQuery()

' tidy up
Command.Dispose()
Command = Nothing
Connection.Close()
Connection = Nothing

' set result
Result = True

Catch ex As Exception

' TODO: Error handling

' tidy up
If Command Is Nothing <> False Then

Command.Dispose()
Command = Nothing

End If

If Connection Is Nothing <> False Then

Connection.Close()
Connection = Nothing

End If

' set flag
Result = False

End Try

' return result
Return Result

End Function

As per my initial post, I only actually set a value to those objects in the "Try" block,
hence the warning...as you suggested, setting them to nothing at the top outside of Try
would obviously clear these up.
And lastly, you do not need to set the variables to Nothing. That was something you had
to do in VB6.


I do that for completeness, I read/heard about .net clearing up after itself as and when
it deems appropriate, I just like to save it the trouble :)

Rob

Nov 19 '05 #6
The same for Connection, btw :

If Connection Then
Connection.Close()
Connection = Nothing
End If
Juan T. Llibre, ASP.NET MVP
ASP.NET FAQ : http://asp.net.do/faq/
Foros de ASP.NET en Español : http://asp.net.do/foros/
======================================
"Juan T. Llibre" <no***********@nowhere.com> wrote in message
news:Od**************@TK2MSFTNGP12.phx.gbl...
re:
I understand what you are saying, and thank you for the reply, however, in my example:

If Command Is Nothing <> False Then
Command.Dispose()
Command = Nothing
End If

I would then have do add more code, ie,


Wouldn't :

If Command Then
Command.Dispose()
Command = Nothing
End If

work better ?

In C#, that works, too :

if (Command) {
Command.Dispose();
Command = null;
}

Juan T. Llibre, ASP.NET MVP
ASP.NET FAQ : http://asp.net.do/faq/
Foros de ASP.NET en Español : http://asp.net.do/foros/
======================================
"Rob Meade" <te**************@edaem.bbor> wrote in message
news:BT**************@text.news.blueyonder.co.uk.. .
"Marina" wrote ...
One comment, is that when you are testing that the result of a boolean expression is
not equal to false - that is really confusing to read. A more readable way is:

If Command Is Nothing = True Then

And, better yet:

If Command Is Nothing Then


Hi Marina,

I understand what you are saying, and thank you for the reply, however, in my example:

If Command Is Nothing <> False Then
Command.Dispose()
Command = Nothing
End If

I would then have do add more code, ie,

If Command Is Nothing Then
' do nothing
Else
Command.Dispose
Command = Nothing
End If

Easier to read - but more code...
Now, in all of the cases above, your If statement will execute, which is not what you
want, since you will get a nullreferenceexception.


But this is why I'm testing it? Am I not saying in the test, if the object is
"something" then kill it off? ie, if its "nothing" (null?) then dont worry...skip
right past...
Which proves my point as to just how confusing writing code like that is.


I'm obviously missing something, it makes sense to me - is what I've replied with above
here wrong then?
Now, the compiler can only do so much in figuring out your code. It may be, that your
code is written in such a way, that an object is always assigned before you use it.
If you want to get rid of the warning, always assign the variable, even if it is to
nothing.


The full chunk is as follows:

Public Function TruncateDatabase() As Boolean

' declare variables
Dim Connection As SqlConnection
Dim Command As SqlCommand
Dim Result As Boolean

' exception handling
Try

' create and open our database connection
Connection = New SqlConnection(ConfigurationManager.AppSettings("We bmasters"))
Connection.Open()

' create and define our command object
Command = New SqlCommand
Command.Connection = Connection
Command.CommandType = CommandType.Text
Command.CommandText = "TRUNCATE TABLE Webmasters"

' execute
Command.ExecuteNonQuery()

' tidy up
Command.Dispose()
Command = Nothing
Connection.Close()
Connection = Nothing

' set result
Result = True

Catch ex As Exception

' TODO: Error handling

' tidy up
If Command Is Nothing <> False Then

Command.Dispose()
Command = Nothing

End If

If Connection Is Nothing <> False Then

Connection.Close()
Connection = Nothing

End If

' set flag
Result = False

End Try

' return result
Return Result

End Function

As per my initial post, I only actually set a value to those objects in the "Try"
block, hence the warning...as you suggested, setting them to nothing at the top outside
of Try would obviously clear these up.
And lastly, you do not need to set the variables to Nothing. That was something you
had to do in VB6.


I do that for completeness, I read/heard about .net clearing up after itself as and
when it deems appropriate, I just like to save it the trouble :)

Rob


Nov 19 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
by: mattvenables | last post by:
If anyone needs a programmer to work on a project, you can e-mail me at mattvenables (-AT-) gmail.com. I am extremely skilled in PHP and many other web languages. Let me know!
13
by: MLH | last post by:
I have a textbox control used to enter a single alphanumeric character. It changes the case of "i" to upper case. But it does not do so with the letter "g". Its left as "g" - not changed to "G"? ...
5
by: Tom | last post by:
Hi, I am working on a project where I want to simultaneously launch a link using my own registered protocol and simultaneously send an AJAX request to the server. Now the way I have come up...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.