Mohanapriya R Mohanapriya R
Updated date Jun 12, 2024
In this article, we will learn how to convert strings to longs in C#. Includes a simple program with output for easy understanding.
  • 4.2k
  • 0
  • 0

How to Convert String to Long in C#?

To convert a string to a long in C#, we can use the long.Parse() method or the long.TryParse() method as shown in the below program,

using System;

class Program
{
    static void Main()
    {
        // String representing a number
        string numberString = "123456789";

        // Using long.Parse() to convert string to long
        try
        {
            long number = long.Parse(numberString);
            Console.WriteLine($"Using long.Parse(): {number}");
        }
        catch (FormatException)
        {
            Console.WriteLine("Invalid format for conversion.");
        }
        catch (OverflowException)
        {
            Console.WriteLine("The number is too large for a long.");
        }

        // Using long.TryParse() to convert string to long
        if (long.TryParse(numberString, out long result))
        {
            Console.WriteLine($"Using long.TryParse(): {result}");
        }
        else
        {
            Console.WriteLine("Conversion failed.");
        }
    }
}

First method, we use long.Parse() within a try-catch block. If the string can be successfully converted to a long, it will be stored in the number variable. If the string is not in the correct format for conversion or if the number is too large for a long, exceptions will be raised and the error messages will be displayed.

Next, we use long.TryParse(). This method attempts to convert the string to a long, but instead of throwing an exception on failure, it returns a boolean indicating success or failure. If successful, the converted value is stored in the result variable. If the conversion fails, we handle it accordingly.

Output:

Using long.Parse(): 123456789
Using long.TryParse(): 123456789

Comments (0)

There are no comments. Be the first to comment!!!