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

王林
Release: 2023-08-22 15:53:07
forward
1532 people have browsed it

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;
   }
}
Copy after login

Output

123
Copy after login

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;
   }
}
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template