473,748 Members | 6,161 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

VS2005: Code "gramatical ly" 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.Clos e()
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 1217
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 nullreferenceex ception.

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.ne ws.blueyonder.c o.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.Clos e()
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.ne ws.blueyonder.c o.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.Clos e()
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 nullreferenceex ception.
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 TruncateDatabas e() 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(C onfigurationMan ager.AppSetting s("Webmasters") )
Connection.Open ()

' create and define our command object
Command = New SqlCommand
Command.Connect ion = Connection
Command.Command Type = CommandType.Tex t
Command.Command Text = "TRUNCATE TABLE Webmasters"

' execute
Command.Execute NonQuery()

' tidy up
Command.Dispose ()
Command = Nothing
Connection.Clos e()
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.Clos e()
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.new s.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 nullreferenceex ception.


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 TruncateDatabas e() 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(C onfigurationMan ager.AppSetting s("Webmasters") )
Connection.Open ()

' create and define our command object
Command = New SqlCommand
Command.Connect ion = Connection
Command.Command Type = CommandType.Tex t
Command.Command Text = "TRUNCATE TABLE Webmasters"

' execute
Command.Execute NonQuery()

' tidy up
Command.Dispose ()
Command = Nothing
Connection.Clos e()
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.Clos e()
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.Clos e()
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******** ******@TK2MSFTN GP12.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.new s.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 nullreferenceex ception.


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 TruncateDatabas e() 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(C onfigurationMan ager.AppSetting s("Webmasters") )
Connection.Open ()

' create and define our command object
Command = New SqlCommand
Command.Connect ion = Connection
Command.Command Type = CommandType.Tex t
Command.Command Text = "TRUNCATE TABLE Webmasters"

' execute
Command.Execute NonQuery()

' tidy up
Command.Dispose ()
Command = Nothing
Connection.Clos e()
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.Clos e()
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
1752
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
1790
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"? Although Access's attempts at keeping me gramatically correct, it isn't helping me in this particular case. Can I turn that behavior off at will - on a case-by-case basis?
5
1453
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 with doing this is by having a normal link (so that the link still works still if JavaScript is disabled) and an onClick handler which makes the XMLHTTP request.
0
8989
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
1
9319
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9243
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6795
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6073
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4599
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4869
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3309
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 we have to send another system
3
2213
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.