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?

BurkDiggler
  • 161
  • 1
  • 8

3 Answers3

12

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

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

The second example could be improved if there existed a null-safe dereferencing operator but since it doesn't exist in C#, your approach is fine:

int id = person == null ? -1 : person.Id;
Community
  • 1
  • 1
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
  • 1
    This does cause an unnecessary `int.Parse("-1")`, though, instead of just setting the value to -1 directly. – Reed Copsey Jul 30 '12 at 19:51
  • 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! – BurkDiggler Jul 30 '12 at 20:12
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.

psubsee2003
  • 8,563
  • 8
  • 61
  • 79
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.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • 1
    IsNullOrWhitespace? and what with everything else that isn't a number? int.TryParse seems a better solution to me. – huysentruitw Jul 30 '12 at 19:58
  • 1
    @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. – Reed Copsey Jul 30 '12 at 20:02