Home >Backend Development >C#.Net Tutorial >How to parse a string into a nullable integer in C#?
#C# provides a special data type, the null type, to which values in the normal range and null values can be assigned.
C# 2.0 introduced nullable types, allowing null to be assigned to value type variables. Nullable types can be declared using Nullable, where T is a type.
Nullable types can only be used with value types.
If value is null, the Value property will throw an InvalidOperationException exception; otherwise, it will return the value.
The HasValue property returns true if the variable contains a value, or false if it is null.
Only == and ! can be used! = operator is used with nullable types. For other comparisons, use the Nullable static class.
Nested nullable types are not allowed. Nullable
static class Program{ static void Main(string[] args){ string s = "123"; System.Console.WriteLine(s.ToNullableInt()); Console.ReadLine(); } static int? ToNullableInt(this string s){ int i; if (int.TryParse(s, out i)) return i; return null; } }
123
When passing Null to the extension method, it does not print any value
static class Program{ static void Main(string[] args){ string s = null; System.Console.WriteLine(s.ToNullableInt()); Console.ReadLine(); } static int? ToNullableInt(this string s){ int i; if (int.TryParse(s, out i)) return i; return null; } }
The above is the detailed content of How to parse a string into a nullable integer in C#?. For more information, please follow other related articles on the PHP Chinese website!