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

CsharpServer Side ProgrammingProgramming

C# provides a special data types, the nullable types, to which you can assign normal range of values as well as null values.

C# 2.0 introduced nullable types that allow you to assign null to value type variables. You can declare nullable types using Nullable where T is a type.

  • Nullable types can only be used with value types.

  • The Value property will throw an InvalidOperationException if value is null; otherwise it will return the value.

  • The HasValue property returns true if the variable contains a value, or false if it is null.

  • You can only use == and != operators with a nullable type. For other comparison use the Nullable static class.

  • Nested nullable types are not allowed. Nullable<Nullable<int>> i; will give 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 Null is passed to the extenstion method it doesn't 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

raja
Published on 07-Nov-2020 12:01:07
Advertisements