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?

3
  • 3
    "some string" is never a valid int. (Except perhaps when using Eldritch culture) Commented Jun 13, 2012 at 20:54
  • No. I will actually have an int value there, it comes from dropdownlist.SelectedItem.Value which comes back as a string Commented Jun 13, 2012 at 21:03
  • possible duplicate of How to use int.TryParse with nullable int? Commented Jun 13, 2012 at 22:42

8 Answers 8

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

Sign up to request clarification or add additional context in comments.

10 Comments

and it always can be done in two simple steps. if performance is an issue here, Parse will be inferior
@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.
according to some benchmarking i have seen it is definitly slower by magnitudes. here it is: blogs.msdn.com/b/ianhu/archive/2005/12/19/505702.aspx in the conclusion
@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.
@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.
|
1

You can use Convert.ToInt32(year).

2 Comments

but this one still throws if string not empty and not a number.
Simplest way. thanks. The DB will make sure its always a number coming in and will do a try catch just to be safe
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);

3 Comments

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

Comments

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");

Comments

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();

Comments

-1

This seems to work also:

int? year;
    if (something)
       year = null;
    else
    {
       int _year;
       int.TryParse(year.SelectedItem.Value, out _year);
       year = _year;
    }

2 Comments

the return value if tryparse should be checked i believe.
Using TryParse without checking the result is only a good idea if you want the value to become default(T), which isn't the case here. You're just hiding a bug if that happens.
-2

Add in some error detection:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.