How to Parse a string to Nullable Int in C# ?

Below is a sample code snippet demonstrating how you can convert a string to Nnullable Int in C#.

How to Parse a string to Nullable Int in C# ?

We use the int.Parse and based on its return value , assign the null or integer value to the Nullable Int.

using System;
using System.Collections.Generic;
using System.Linq;

namespace ACCode
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = "1";
            int? IntNullable;
            int i;
            if (Int32.TryParse(str, out i))
            {
                IntNullable = i;
            }
            else
            {
                IntNullable = null;
            }
            Console.WriteLine(IntNullable);
            Console.ReadLine();
        }       
    } 
}
Tags :

Leave Your Comment

Liked this content?. Please spread the word :)