Click here to Skip to main content
15,911,711 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I couldn't store null value to an integer variable using these codes ....

C#
int? i = Convert.ToInt32(orderqty.Text);
            int? counts = !string.IsNullOrEmpty(orderqty.Text) ? i : (int?)null;

            int? i1 = Convert.ToInt32(yarncounts.Text);
            int? counts1 = !string.IsNullOrEmpty(yarncounts.Text) ? i1 :(int?)null;

Is there any best methods to store null values to counts1 variable ??
Posted

Why?
That is some odd code: you do a conversion to integer - which will fail is the string is empty - then test to see if it's null or empty...
Check first, then convert:
C#
int? counts1 = string.IsNullOrEmpty(yarncounts.Text) ? (int?)null : int.Parse(yarncounts.Text);
 
Share this answer
 
You should optimize the code like this:
int? counts1 = (string.IsNullOrEmpty(yarncounts.Text) ? (int?)null : Convert.ToInt32(yarncounts.Text);
 
Share this answer
 
It isn't necessary to cast the null to (int?).
Also, using int.TryParse would catch other invalid input:
C#
int? counts1 = null;
int i1;
if (int.TryParse(yarncounts.Text, out i1))
{
  counts1 = i1;
}
else
{
  // here you can perform any additional error handling/reporting (but you don't HAVE to!)
}
 
Share this answer
 
Comments
phil.o 29-Apr-14 13:22pm    
Quote: 'It isn't necessary to cast the null to (int?).'
I'm pretty sure it is :) Due to the "() ? :" construction : the compiler expects both arguments around the colon to be of the same unambiguous type.
Anyway voted 5 as your solution is as valid as both others :)
Matt T Heffron 29-Apr-14 13:32pm    
Yes, I wasn't thinking in the context of the ?:

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900