testing null for integer type variable

  • Thread starter Thread starter js
  • Start date Start date
J

js

I need to test if an integer variable is null or not. I tried to do

int myVairable;
myVariable = Int32.Parse(txtControl1.Text.Trim());
if (myVariable != null) {// do something}

C# does not allow this statement. How do I test an integer to see if it
is null or not? Thanks.
 
The Parse method will throw an ArgumentNullException if the value being
passed is nothing. You can use a Try/Catch to catch the
ArgumentNullException. I'm not a C# programmer, but in VB it would look like:

dim myVariable as integer
Try
myVariable = Int32.Parse(txtControl1.Text.Trim())
'If I get here then all is well. Do something with the number.
myVariable = myVariable * 5

Catch exane as ArgumentNullException
'Value is null; do something else:
lblError.Text = exane.Message

Catch ex as Exception
'To catch all other errors
lblError.Text = ex.Message
End try

Hope this helps.
 

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

Back
Top