Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

int.TryParse = null if not numeric?

Tags:

c#

.net

tryparse

is there some way of return null if it can't parse a string to int?

with:

public .... , string? categoryID) 
{
int.TryParse(categoryID, out categoryID);

getting "cannot convert from 'out string' to 'out int'

what to do?

EDIT:

No longer relevant because of asp.net constraints is the way to solve problem

/M

like image 750
Lasse Edsvik Avatar asked Nov 13 '09 14:11

Lasse Edsvik


People also ask

What does TryParse mean?

TryParse(String, Int32) Converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the conversion succeeded.

What happens if int TryParse fails?

TryParse method converts a string value to a corresponding 32-bit signed integer value data type. It returns a Boolean value True , if conversion successful and False , if conversion failed. In case of failed conversion, it doesn't throw any exception and 0 is assigned to the out variable.

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.

What does TryParse return if successful?

When this method returns, contains the 32-bit signed integer value equivalent to the number contained in s, if the conversion succeeded, or zero if the conversion failed. But what happens if the passed string itself is a string representation of '0'. So the TryParse will return zero.


1 Answers

How about this?

public int? ParseToNull(string categoryId)
{
    int id;
    return int.TryParse(categoryId, out id) ? (int?)id : null;
}
like image 116
DigitalNomad Avatar answered Oct 22 '22 12:10

DigitalNomad