Difference between (int) and convert.toint32 in C #

when i convert an object to int using

(int)object

then when the value of the object is 0, it gives me an error that a particular action is invalid.

when i convert an object to int using

convert.toint32(object)

then it works and gives me 0, which means the acts are valid.

and I want to know what the difference is between them.

1. (int)object
2.convert.toint32(object)
+2
source share
5 answers

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

The biggest thing to remember is error checking, none of the methods is proof of a fool yourself, so you need to decide how you want to approach them.

(int), Convert.ToInt32(), int.Parse() , InvalidCastException, FormatException OverflowException, try/catch .

int.TryParse() / , out, .

int, , , Convert.ToInt32, :

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

, .ToString(), :

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

(int) , . , (int) "12" .

Convert.ToInt32 , , . , Convert.ToInt32("12") 12. , IConvertible ( System.String), Convert.ToInt32 IConvertible.ToInt32.

+12

. - casting, - conversion.

conversion , non-integer int.

casting unbox int, int, Object.

+3

(Type)val :

  • (, float an int),
    • (float < === > int )
    • beefit (, int < === > an-int-enum)
  • ( , )
    • (, === > IDataReader)
    • (, IDataReader === > )
  • / ( [ a Nullable<T>]
  • ( ),

object, (int)object , unboxing, , int ( int-enum), , - float ..

Convert.ToInt32 -; , , casting-from-a-float ( ) ( int.Parse).

+3

, (int) something :

  • something - int, , . , , int ArrayList HttpSession ..

  • something not int, but its type can be explicitly converted to int, for example, short, long, float from built-in types or a type that implements an explicit casting operator.

Convert.ToInt32, on the other hand, simply calls a method somethinglike IConvertible.ToInt32 and is more or less equivalentint.Parse(something)

+2
source

Source: https://habr.com/ru/post/1750373/


All Articles