What is difference between the following cast/convert.
string a = 5;
int b = (int)a;
int c = a as int;
int d = Convert.ToInt32(a);
Just curious to know about these different methods and where to use them accordingly.
What is difference between the following cast/convert.
string a = 5;
int b = (int)a;
int c = a as int;
int d = Convert.ToInt32(a);
Just curious to know about these different methods and where to use them accordingly.
(int)a
is simply a cast to the Int32 type and requires a
to be a numeric value (float, long, etc.)
Convert.ToInt32(a)
will properly convert any data type to int - including string
s - instead of just casting it to another type.
a as int
is the same implicit conversion (casting) as (int)a
therefore they both do roughly the same thing.
Points to note:
as
can only be used with nullable/reference types and int
in non-nullable. use int?
with as
(int)long
will return an exception while long as int?
will return null