3

Here's something that's not really an issue and I apologize if it's a stupid question but it's just something I'm curious about. Let's say I want to parse a string parameter as an integer if the string is not null, otherwise set the integer to -1. Is there a better way to write this statement:

int id = context.Request["Id"] == null ? -1 : int.Parse(context.Request["Id"]);

It just seems messy to have to evaluate the string to see if it's null and then evaluate it again to parse it. Now that I think about it, this has come up with objects and accessing an objects properties if it isn't null. So something like:

int id = person == null ? -1 : person.id;

Is this the accepted practice?

3 Answers 3

12

For your first example, you can use the null coalescing operator:

int id = int.Parse(context.Request["Id"] ?? "-1");

For your second example, you can use the null-conditional operator:

int id = person?.Id ?? -1;
Sign up to request clarification or add additional context in comments.

2 Comments

This does cause an unnecessary int.Parse("-1"), though, instead of just setting the value to -1 directly.
I didn't even think to make the null check while passing the parameter into the parse method, doh! It seems so simple now. And yes the null-safe dereferencing operator is exactly what I was looking for, good to know that it exists, just not for C#. Thanks!
3

You didn't state whether int.Parse() has the potential to fail for non-null values, but if you aren't certain a non-null input string will always be an int value, you can also use the TryParse() method:

int id;
if (!int.TryParse(context.Request["Id"], out id)
    id = -1;

This will not throw an exception if context.Request["Id"] is null, or if it is not parsable to int.

2 Comments

that looks exaclty like my answer :) Seems like we were typing the same chars at exaclty the same moment.
anyway +1 for this, as it is much better to be prepared for non-numeric input instead of catching an exception.
1

Personally, I would make this two statements:

string tmp = context.Request["Id"];
int id = String.IsNullOrWhitespace(tmp) ? -1 : int.Parse(tmp);

This handles this without any extra parsing. Doing this in one line will require an extra lookup of the context (which you were trying to avoid) or extra parsing.

2 Comments

IsNullOrWhitespace? and what with everything else that isn't a number? int.TryParse seems a better solution to me.
@WouterH Yes - this doesn't handle non-numeric input - but it was really more a matter of trying to address the specific question regarding handling nulls vs. int parsing.

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.