Search code examples
c#parsingnull

C# Parse value if not null


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?


Solution

  • 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;