How to safely convert to Integer possible null values


You could inline a TryParse with a ternary expression, provided you have a default value in mind for Id when it's null.

var data = mockDataDB.Data.AsQueryable()
   .Select(x => new ProductDto
   {
       Id = Int64.TryParse(x.id, out long val) ? val : 0L, 
       Quantity = Int32.TryParse(x.quantity, out int somenumber) ? somenumber : (int?)null
   }

The pattern matching is statement doesn't allow a nullable value type, such as int? or Nullable<int>, but you can test for any other value type. The is patterns from the preceding example are not limited to the nullable value types. You can also use those patterns to test if a variable of a reference type has a value or it's null.


Something like this: Id = Int64.TryParse(x.id, out int somenumber) ? somenumber : 0

The Option<T> has an implicit conversion from the null or the T type. So if the Find method returns null, it will be converted to an especial derivation of Option<Movie> a None. An Option<T> will either contain a value of the type T (in this case a movie instance), or it will contain an especial type known as None.


Edited: You should check if the String variable (x.id) is null. If it is, you set it to zero or some default value that you would want. If its not, proceed with the converting. For example:

Id = (x.id == null) ? 0 : Convert.ToInt64(x.id);

You can use a couple built in methods, as shown below, to convert a string to int. Both of these would throw an exception if the string value is not a valid integer. int.Parse((string) null); // throws exception int.Parse("Hello"); // throws exception int.Parse("1.5"); // throws exception var i = int.Parse("1"); // Works!


c# - How to safely convert to Integer possible null values - Stack Overflow. var data = mockDataDB.Data.AsQueryable() .Select(x =&gt; new ProductDto { Id = Convert.ToInt64(x.id), // this might fail because id might be null Quantity = Int32.TryParse(x.qu Stack Overflow. Products.


Converting a String to an int or Integer is a very common operation in Java. In this article, we will show multiple ways of dealing with this issue. In this article, we will show multiple ways of dealing with this issue.


An expression that evaluates to one or more values, such as a column name or a literal. Converting null values returns nulls. The expression cannot contain blank or empty strings. type. One of the supported Data types.