1

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?

sd_dracula
  • 3,796
  • 28
  • 87
  • 158
  • 3
    `"some string"` is never a valid int. (Except perhaps when using Eldritch culture) – CodesInChaos Jun 13 '12 at 20:54
  • No. I will actually have an int value there, it comes from dropdownlist.SelectedItem.Value which comes back as a string – sd_dracula Jun 13 '12 at 21:03
  • possible duplicate of [How to use int.TryParse with nullable int?](http://stackoverflow.com/questions/3390750/how-to-use-int-tryparse-with-nullable-int) – George Stocker Jun 13 '12 at 22:42

8 Answers8

9

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).

Douglas
  • 53,759
  • 13
  • 140
  • 188
  • and it always can be done in two simple steps. if performance is an issue here, Parse will be inferior – Mare Infinitus Jun 13 '12 at 20:53
  • @MareInfinitus: I doubt that it’s significantly less efficient than `TryParse` (which still needs to perform validation). It may be less efficient than a manual implementation that skips all validation checks, but it’s usually not worth the trouble. – Douglas Jun 13 '12 at 20:56
  • according to some benchmarking i have seen it is definitly slower by magnitudes. here it is: http://blogs.msdn.com/b/ianhu/archive/2005/12/19/505702.aspx in the conclusion – Mare Infinitus Jun 13 '12 at 21:04
  • @MareInfinitus: It will be significantly slower if it throws (as is the case with throwing exceptions in general), not if it always succeeds. I’ve checked the internal implementations of `Parse` and `TryParse`, and apart from throwing vs returning false, they’re identical. – Douglas Jun 13 '12 at 21:08
  • @MareInfinitus: From that article: “All of these functions take about the same time with good data.” The results of the tests with the bad data are irrelevant, since the OP guaranteed that the string will always be valid. – Douglas Jun 13 '12 at 21:11
  • i prefer generic, reuseable solutions over "will work for this case" approaches. just a matter of taste though – Mare Infinitus Jun 13 '12 at 21:11
  • @MareInfinitus: If the OP said that the string will *always* be valid, then `Parse` is the correct way to go. If you think one should always use `TryParse`, then that’s just your personal opinion. – Douglas Jun 13 '12 at 21:16
  • 3
    @MareInfinitus The choice is about intent. Using `Parse` says "This will always be valid. If it's invalid, we have a bug, so no need to handle that case." whereas `TryParse` says "It can sometimes be invalid, and I've added explicit error handling for it". In most cases the right choice is quite obvious, and since the OP said that the value is guaranteed to be a valid int, `Parse` is clearly the better choice here. – CodesInChaos Jun 13 '12 at 21:20
  • as stated, this is my preference, as I try to avoid "works here and now" approaches. – Mare Infinitus Jun 13 '12 at 21:31
  • @CodeInChaos: Good explanation re “intent”. I need to learn to factor that into my justifications more often. – Douglas Jun 13 '12 at 21:32
1

You can use Convert.ToInt32(year).

m03geek
  • 2,508
  • 1
  • 21
  • 41
1

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);
Mare Infinitus
  • 8,024
  • 8
  • 64
  • 113
  • Just because you didn't get an upvote, please don't go and downvote all the other option. We are all giving up our time to help people out because other people help us out. If you don't like my answer, just commment below it. And if someone give a stupid answer, then down vote to indicate that it is a bad answer – Gerhard Powell Jun 13 '12 at 21:32
  • it may look i was this, but i did not, as you can see from that I did not loose any reputation. (think you get -1 for downvoting, or?) ... if i think somewhat is broken, i leave an comment on that. and you can see many comments by me here... 490 entering here, 490 leaving here, no problem for me, just wanted to leave the solution that seems to be the best for me. – Mare Infinitus Jun 13 '12 at 21:34
  • 1
    no problem, as i wondered myself who would do that. discussion is always better than plain downvote, as i believe everybody can learn something, even he is skeet or gossman. and if anybody thinks something is wrong in what i believe is the best solution, i definitly want to know that. – Mare Infinitus Jun 13 '12 at 21:43
0

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

Seth Flowers
  • 8,990
  • 2
  • 29
  • 42
0

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");
Ben S
  • 185
  • 1
  • 10
0
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();

Chris Marisic
  • 32,487
  • 24
  • 164
  • 258
-1

This seems to work also:

int? year;
    if (something)
       year = null;
    else
    {
       int _year;
       int.TryParse(year.SelectedItem.Value, out _year);
       year = _year;
    }
sd_dracula
  • 3,796
  • 28
  • 87
  • 158
-2

Add in some error detection:

try
{
   year = int.Parse("some string");
}
catch()
{
   year = null;
}
Gerhard Powell
  • 5,965
  • 5
  • 48
  • 59