13

is there some way of return null if it can't parse a string to int?

with:

public .... , string? categoryID) 
{
int.TryParse(categoryID, out categoryID);

getting "cannot convert from 'out string' to 'out int'

what to do?

EDIT:

No longer relevant because of asp.net constraints is the way to solve problem

/M

4
  • 2
    Why do you parse it to an int when you want to store it in a string?? Commented Nov 13, 2009 at 14:17
  • 2
    By the way, string is a reference type, so you should not make it nullable. (does this compile anyway?) Commented Nov 13, 2009 at 14:17
  • I use this for asp.net mvc so the categoryID is mapped from the url, so I get error if i pass in string in url Commented Nov 13, 2009 at 14:20
  • @Stefan: My guess is that the OP is validating string format using this method as well as enforcing a fixed string format. Therefore, they can parse 10,000 and turn it into 10000, for example. Just a guess though. Commented Nov 13, 2009 at 14:29

8 Answers 8

28

First of all, why are you trying to parse a string to an int and stick the result back into a string?

The method signature is

bool int.TryParse(string, out int)

so you have to give a variable of type int as second argument. This also means that you won't get null if parsing fails, instead the method will simply return false. But you can easily piece that together:

int? TryParse2(string s) {
    int i;
    if (!int.TryParse(s, out i)) {
        return null;
    } else {
        return i;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Eep, thanks, Garry. Writing code without ever compiling it invites errors such as those :-)
I bet this would make a nice extension method
14

Here's a proper use of Int32.TryParse:

int? value;
int dummy;
if(Int32.TryParse(categoryID, out dummy)) {
    value = dummy;
}
else {
    value = null;
}
return value;

3 Comments

Or: value = int.TryParse(categoryID, out dummy) ? dummy : null;
Yes, absolutely but that's more opaque to a neophyte.
@Dan: won’t compile ;-) But yes, I prefer that solution (plus one cast, to make it compile).
10

How about this?

public int? ParseToNull(string categoryId)
{
    int id;
    return int.TryParse(categoryId, out id) ? (int?)id : null;
}

5 Comments

This solution might benefit from being turned into an extension method.
It's already an extension method in my app but I didn't know what molgan wanted it for so I kept it as a method.
you don't need the cast on id there. An int or a null is a valid Nullable<int> :).
@Khanzor: Actually, you do, unless you replace null with new int?(). Otherwise, the type of the conditional cannot be inferred.
@SLaKs - Ahh, so he does. If you don't use the ternary operator you can avoid the cast though.
2

Simplest and one-liner...

int N = int.TryParse(somestring, out N) ? N : 0;

It works 'cause it's evaluated left to right. Null not so easy.

Comments

0

TryParse will return false if the string can't be parsed. You can use this fact to return either the parsed value, or null. Anyway I guess that you are intending to return int? from your method, then it would be something like this:

public int? ParseInt(string categoryID) 
{
    int theIntValue;
    bool parseOk = int.TryParse(categoryID, out theIntValue);
    if(parseOk) {
        return theIntValue;
    } else {
        return null;
    }
}

Comments

0

Do you want to do something like this?

public int? Parse(string categoryID) 
{
  int value;
  if (int.TryParse(categoryID, out value))
  {
    return value;
  }
  else
  {
    return null;
  }
}

Comments

0

Int is a value type which means there is no such thing as a null int. So no, TryParse will never alter the out parameter so that it is null.

But the problem you're having is you're passing a string to the out parameter of TryParse when its expecting an integer.

You need something like this...

Int categoryID = 0;
string strCategoryID = "somestringmaybeitsaninteger";

int.TryParse(strCategoryID, out categoryID);

3 Comments

There is a nullable int: int?
Dani: TryParse however, returns int, not Nullable<int>.
int? is not actually an integer type ... it's shorthand for System.Nullable<int>.
0

** this answer was down-voted a lot ** Although it is a possible solution - it is a bad one performance wise, and probably not a good programming choice.

I will not delete it, as I guess many programmers might not be aware of this, so here is an example how not to do things:

use try and catch

try
{
res = Int32.Parse(strVAR)
}
catch(exception ex) 
{
 return null;
}

17 Comments

Since C# 2.0 came out, TryParse is almost always better than doing exception catching.
It's an option, but it's a bad one - hence all the downvotes.
I will be happy to understand why it is bad (performance ?) ?
Exceptions should not, as a practice, be a part of the normal flow of code. They should be exactly as their name implies, an exception. If you are expecting certain things on a regular basis, you should try to code a solution rather than throwing an exception and handling it. An example is checking if a file exists prior to trying to open it rather than opening a file and catching a file not found exception. So in general, avoid exception programming if you don't need it. In other words, save it for the exceptions... :)
+1 Because although it's incorrect, it does show a valid way that someone could solve a problem such as this. Since the poster edited his answer to show that it was incorrect, and left comments as to why, I see no reason that it should be given such a low ranking.
|

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.