Converting a string to int?

Asked

Viewed 11,946 times

11

How best to convert a variable string for another variable of the type int?, namely, a nullable of int? Performance is very important in this case because I will be converting several values within a loop.

Would it be possible to do this conversion on a line of code? I ask this because there will be many consecutive lines of code doing this operation and it would be a "plus" if it did not increase my code a lot with data conversion.

  • If you have a list of strings (or IEnumerable<string>) to convert, could use LINQ, as I indicated in my reply. You can do it in 2 or 3 lines of code like this... depending on the code formatting you use.

6 answers

6

You can also implement the @Miguelangelo response in class extension form:

namespace SeuProjeto.Extensions 
{
    public static class StringExtension 
    {
        public static Nullable<int> ToInt(this String value) 
        {
            int outInt;
            return int.TryParse(value, out outInt) ? outInt : (int?)null;
        }
    }
}

The same example in LINQ would look like this:

var strNumeros = new[] { "1267", "-835", "9", "", "xpto" };
int outInt;
var valores = strNumeros
    .Select(strNumero => strNumero.ToInt())
    .ToList();

5


You can use the following function to make the conversion effectively and without many lines:

public static int? StringToNullableInt(string strNum)
{
    int outInt;
    return int.TryParse(strNum, out outInt) ? outInt : (int?)null;
}

Or else to do the inline conversions, using LINQ, you could do so:

var strNumeros = new[] { "1267", "-835", "9", "", "xpto" };
int outInt;
var valores = strNumeros
    .Select(strNumero => int.TryParse(strNumero, out outInt) ? outInt : (int?)null)
    .ToList();

This way you convert all the strings into one IEnumerable<string> in almost a few lines.

4

It is possible that there are several ways to do it. I use the TryParse to convert string for int.

Example:

var varStringConvert = "123";
int varInt;
if ((int.TryParse(varStringConvert.ToString(), out varInt))) { 

}

The code above shows the variable varStringConvert with the value 123 which is integer but compiler as does not guess and thinks it is a variable of type string. Then we have to try to convert to whole. So I do one TryParse of string for the variable int varInt.

2

The class can be used Convert. to convert a string defined above, for example:

string name = "12345";

Convert.Toint32(name);

  • 1

    It also works, but if you don’t do the conversion, you get an error

1

Converts and checks whether you were able to convert:

string str = '0123'; // ou qualquer coisa
int i = 0; // inicializa variável que receberá o valor inteiro

// Tenta converter str para inteiro (com saída na variável i)
if (Int32.TryParse(str, out i)) {
    Console.WriteLine(i); // Se conseguiu imprime variável
} else {
    Console.WriteLine ("Erro ao converter '" + str + "' para inteiro."); // Mensagme de erro
}

or

string str = '0123'; // ou qualquer coisa
int i = 0; // inicializa variável que receberá o valor inteiro    
try
{
    i = Convert.ToInt32(str);
    Console.WriteLine(i); // Se conseguiu imprime variável
}
catch (FormatException e)
{
    Console.WriteLine("String inválida para conversão."); // Erro
}
catch (OverflowException e)
{
    Console.WriteLine ("Overflow. Valor inteiro ultrapassou o limtie."); // Erro
}

Create a specific class to solve this and call a method you will trust, that is, you will invoke a method to solve this conversion and you will make sure that even if the string is invalid it will return an integer value to you.

Example, if you only need positive integer values, whenever the function returns you -1 it would be a sign that you gave error. Etc.

Code maintenance would be done and in only one location, within this method in the particular class that solves this conversion problem.

Performance is not a direct influence on both cases. If you are sure that the value is integer, not checking would gain little performance, which in my opinion is not worth, since a 'crash' in the application would be worse if your function received a string that does not contain a possible integer value.

0

There are at least three types of conversions (Parse, Tryparse and Convert), ideally, you would understand how they work and use them according to your need.

You can understand more about them in the post I leave below written by Vitor Mendes (MVP) who explains this subject:

Parse, Convert or Tryparse

Browser other questions tagged

You are not signed in. Login or sign up in order to post.