Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use int.TryParse with nullable int? [duplicate]

Tags:

c#

I am trying to use TryParse to find if the string value is an integer. If the value is an integer then skip foreach loop. Here is my code.

string strValue = "42 "   if (int.TryParse(trim(strValue) , intVal)) == false  {     break;  } 

intVal is a variable of type int?(nullable INT). How can I use Tryparse with nullable int?

like image 548
nav100 Avatar asked Aug 02 '10 18:08

nav100


People also ask

How do I parse a string to a nullable int?

To parse a string into a nullable int we can use the int. TryParse() method in c#.

Why should one use TryParse instead of parse?

Parse() method throws an exception if it cannot parse the value, whereas TryParse() method returns a bool indicating whether it succeeded. However, TryParse does not return the value, it returns a status code to indicate whether the parse succeeded and does not throw exception.

What is the difference between int parse and int TryParse?

TryParse method returns false i.e. a Boolean value, whereas int. Parse returns an exception.


1 Answers

Here's an option for a nullable int with TryParse

public int? TryParseNullable(string val) {     int outValue;     return int.TryParse(val, out outValue) ? (int?)outValue : null; } 
like image 187
PsychoCoder Avatar answered Sep 21 '22 06:09

PsychoCoder