Home  >  Article  >  Backend Development  >  How to parse a string into a nullable integer in C#?

How to parse a string into a nullable integer in C#?

王林
王林forward
2023-08-22 15:53:071531browse

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> i; will cause a compile-time error.

Example 1

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;
   }
}

Output

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;
   }
}

output

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete