Reputation: 3896
I need to sometimes set the value of an int to null and sometimes to an actual value. The problem is I need to store that value in the SAME variable not create another.
int? year;
if(something)
year = null;
else
int.tryParse("some string", out year);
"some string" is always a valid int but the problem is I can't use int.tryParse on int? How to get around that?
Upvotes: 1
Views: 3598
Reputation: 33098
public static class StringExtensions
{
public static int? AsInt(this string input)
{
int number;
if (int.TryParse(input, out number))
{
return number;
}
return null;
}
}
Usage: year = someString.AsInt();
Upvotes: 0
Reputation: 185
int.tryParse returns a boolean, not just the out value - you can do this also:
int year;
int? finalYear;
if(int.TryParse("some string", out year))
finalYear = year;
otherwise, if "some string" will always return a valid int, why not do
int? year = int.Parse("some string");
Upvotes: 0
Reputation: 3896
This seems to work also:
int? year;
if (something)
year = null;
else
{
int _year;
int.TryParse(year.SelectedItem.Value, out _year);
year = _year;
}
Upvotes: -1
Reputation: 8162
You could try this:
public class NullInt
{
public void ParseInt(string someString, ref int? someInt)
{
int i;
if (int.TryParse(someString, out i))
{
someInt = i;
}
}
}
and used somewhat like:
NullInt someInt = new NullInt();
int? targetInt = null;
someInt.ParseInt("42", ref targetInt);
Upvotes: 1
Reputation: 6175
Add in some error detection:
try
{
year = int.Parse("some string");
}
catch()
{
year = null;
}
Upvotes: -2
Reputation: 9190
If "some string" is always a valid int, then you COULD just convert it to an int, using System.Convert.ToInt32 or System.Int32.Parse
Upvotes: 0