How to Convert String to Int Without Parse in C#.Net

In this C#.Net tutorial, we will discuss, how to convert string to int without parse in C#.Net.

We can convert string to int without parse in C#.Net by using the Convert.ToInt32() function.

Convert String to Int in C#.Net by using Convert.ToInt32()

The Convert.ToInt32() method belongs to the Convert class in the System namespace, which is a part of .NET’s Base Class Library (BCL). This method converts a wide range of types to integers, including strings.

The syntax for Convert.ToInt32() is as follows:

int Convert.ToInt32(string value)

The method takes a string as an argument and returns an integer. The string argument should contain a number; otherwise, a FormatException will be thrown.

Here’s a simple example:

string str = "1234";
int num = Convert.ToInt32(str);
Console.WriteLine(num);

The output will come like below:

1234

Here is the complete code.

using System;

class Program {
    static void Main() {
        string str = "1234";
        int num = Convert.ToInt32(str);
        Console.WriteLine(num);
    }
}

You can see the output:

convert string to int without parse in C#.Net
convert string to int without parse in C#.Net

This is how to convert a string to int without parse in C#.Net.

Handling Non-Numeric Strings

What happens if you try to convert a non-numeric string to an integer in C# using Convert.ToInt32()? Let’s see:

using System;

class Program {
    static void Main() {
        string str = "Hello";
        int num = Convert.ToInt32(str);
        Console.WriteLine(num);
    }
}

When you run this code, you will get a FormatException, because the string “Hello” cannot be converted to an integer. The exact message will come like below:

System.FormatException: ‘Input string was not in a correct format.’ It looks like below:

System.FormatException: 'Input string was not in a correct format
Input string was not in a correct format

To handle this, we can use a try/catch block to catch any exceptions that might be thrown when trying to convert a string to an integer:

using System;

class Program {
    static void Main() {
        string str = "Hello";
        try {
            int num = Convert.ToInt32(str);
            Console.WriteLine(num);
        }
        catch (FormatException) {
            Console.WriteLine("The string could not be converted to an integer.");
        }
    }
}

Now when you run the program, instead of crashing with a FormatException, it will print “The string could not be converted to an integer.”

Convert String to Int with Linq

Another method you can use to convert a string to an integer in C# is by utilizing the System.Linq namespace. Here’s how you can do it.

This approach involves converting each individual character in the string to its numeric representation and then summing up these values to get the final integer. This approach only works with non-negative integers.

Let’s consider an example where we convert a string to an integer using Linq.

First, we need to import the necessary namespaces:

using System;
using System.Linq;

Next, define a string that consists of a numeric value:

string str = "1234";

To convert this string to an integer, we use the Aggregate() method from Linq, which applies an accumulator function over a sequence. In this case, we’re applying a function that multiplies the current total by 10 and adds the next number:

int num = str.Aggregate(0, (result, ch) => result * 10 + ch - '0');

The '0' in the code is the Unicode character ‘0’, which is subtracted from the current character to get its numeric value.

Lastly, print the result to the console:

Console.WriteLine(num);

Here’s the complete code:

using System;
using System.Linq;

class Program {
    static void Main() {
        string str = "1234";
        int num = str.Aggregate(0, (result, ch) => result * 10 + ch - '0');
        Console.WriteLine(num);
    }
}

When you run this program, it will print 1234 to the console.

Handling Non-Numeric Strings

Like Convert.ToInt32(), this method does not inherently handle non-numeric strings. Attempting to convert a non-numeric string with this method will likely result in an incorrect result. For example, trying to convert the string “Hello” using this method will return 29234652 instead of throwing a FormatException.

To handle non-numeric strings, you can add a check before the conversion to ensure the string only contains digits:

using System;
using System.Linq;

class Program {
    static void Main() {
        string str = "Hello";
        if (str.All(char.IsDigit)) {
            int num = str.Aggregate(0, (result, ch) => result * 10 + ch - '0');
            Console.WriteLine(num);
        } else {
            Console.WriteLine("The string could not be converted to an integer.");
        }
    }
}

Now, if the string is non-numeric, the program will print “The string could not be converted to an integer.”

Conclusion

Converting a string to an integer without using int.Parse() or int.TryParse() in C# can be done using the Convert.ToInt32() method. However, unlike the TryParse method, it doesn’t provide a built-in mechanism for handling strings that cannot be converted to integers.

It’s important to incorporate error-handling mechanisms when using Convert.ToInt32(), to ensure your program doesn’t crash when it encounters a non-numeric string. A try/catch block is one effective way to handle these potential exceptions.

You may also like: