sd_dracula
sd_dracula

Reputation: 3896

c# int.tryParse nullable ints how to?

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

Answers (8)

Chris Marisic
Chris Marisic

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

Ben S
Ben S

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

sd_dracula
sd_dracula

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

Mare Infinitus
Mare Infinitus

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

Gerhard Powell
Gerhard Powell

Reputation: 6175

Add in some error detection:

try
{
   year = int.Parse("some string");
}
catch()
{
   year = null;
}

Upvotes: -2

m03geek
m03geek

Reputation: 2538

You can use Convert.ToInt32(year).

Upvotes: 1

Seth Flowers
Seth Flowers

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

Douglas
Douglas

Reputation: 54877

If your string will always be a valid integer, you should just use the Parse method.

year = int.Parse("some string");

In the case that it’s not a valid integer, you will get a FormatException or OverflowException (unlike TryParse, which merely returns false).

Upvotes: 9

Related Questions