Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse a string into a nullable int

I'm wanting to parse a string into a nullable int in C#. ie. I want to get back either the int value of the string or null if it can't be parsed.

I was kind of hoping that this would work

int? val = stringVal as int?; 

But that won't work, so the way I'm doing it now is I've written this extension method

public static int? ParseNullableInt(this string value) {     if (value == null || value.Trim() == string.Empty)     {         return null;     }     else     {         try         {             return int.Parse(value);         }         catch         {             return null;         }     } }    

Is there a better way of doing this?

EDIT: Thanks for the TryParse suggestions, I did know about that, but it worked out about the same. I'm more interested in knowing if there is a built-in framework method that will parse directly into a nullable int?

like image 799
Glenn Slaven Avatar asked Sep 05 '08 00:09

Glenn Slaven


2 Answers

int.TryParse is probably a tad easier:

public static int? ToNullableInt(this string s) {     int i;     if (int.TryParse(s, out i)) return i;     return null; } 

Edit @Glenn int.TryParse is "built into the framework". It and int.Parse are the way to parse strings to ints.

like image 198
Matt Hamilton Avatar answered Sep 22 '22 10:09

Matt Hamilton


You can do this in one line, using the conditional operator and the fact that you can cast null to a nullable type (two lines, if you don't have a pre-existing int you can reuse for the output of TryParse):

Pre C#7:

int tempVal; int? val = Int32.TryParse(stringVal, out tempVal) ? Int32.Parse(stringVal) : (int?)null; 

With C#7's updated syntax that allows you to declare an output variable in the method call, this gets even simpler.

int? val = Int32.TryParse(stringVal, out var tempVal) ? tempVal : (int?)null; 
like image 41
McKenzieG1 Avatar answered Sep 26 '22 10:09

McKenzieG1