Search code examples
c#programming-languages

difference between (int) and convert.toint32 in c#


when i convert a object to int by

(int)object

then when the object value is 0 then he give me error that specific cast not valid.

when i convert a object to int by

convert.toint32(object)

then he works and give me 0 means cast is valid.

and i want to know that what is difference between both.

1. (int)object
2.convert.toint32(object)

Solution

  • There are many ways to convert to an int, a lot depends on what your source is.

    The biggest thing to keep in mind is error checking, none of the methods are fool proof on their own and so you need to decide how you want to approach them.

    Casting with (int), Converting with Convert.ToInt32(), Parsing with int.Parse() all can generate exceptions such as InvalidCastException, FormatException and OverflowException and should use try/catch to handle failed result.

    Parsing with int.TryParse() will return a true/false result of if the parsing was successful and if successful set the value to the out parameter given in the function call.

    If you are truly trying to take any object and turn it into an int, you are probably best with Convert.ToInt32 such as:

    public void TestFunction(object input)
      try {
        int value = Convert.ToInt32(input);
        SomeOtherFunction(value);
      }
      catch (Exception ex) {
        Console.WriteLine("Could not determine integer value");
      }
    }
    

    Another possibility would be relying on the object producing a usable value in .ToString() such as:

    public void TestFunction(object input)
      try {
        int value = int.Parse(input.ToString());
        SomeOtherFunction(value);
      }
      catch (Exception ex) {
        Console.WriteLine("Could not determine integer value");
      }
    }