1

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.

DividedByZero
  • 4,333
  • 2
  • 19
  • 33
soccer7
  • 3,547
  • 3
  • 29
  • 50
  • 2
    How about reading the documentation? – Mephy Oct 19 '14 at 14:01
  • Note also you can't use `as int` because it is not nullable, it has to be `as int?`. – Mephy Oct 19 '14 at 14:03
  • 2
    I assume you read the documentation before asking this question. When you did that, you must also have read about the peculiarities of `(int)`, `as int` and `Convert.ToInt32()`. So our question to you: what was unclear about them? – Jeroen Vannevel Oct 19 '14 at 14:03
  • All three mentioned explanations can be found in Jon Skeet's Awesome answer. – Bhushan Firake Oct 19 '14 at 14:06

1 Answers1

3

(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 strings - 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
DividedByZero
  • 4,333
  • 2
  • 19
  • 33
  • `string as int` *cannot* return null because the type it returns must be an `int`. – Chris Oct 19 '14 at 14:21
  • @Chris from MSDN: `The as operator is like a cast operation. However, if the conversion is not possible, as returns null instead of raising an exception` – DividedByZero Oct 19 '14 at 14:27
  • from actually trying that code: "The as operator must be used with a reference type or nullable type ('int' is a non-nullable value type)" I assume that the docs say that somewhere too. To clarify this is because the return type of `myvar as T` is `T` and if T is int then it cannot return null because `int` is a value type that cannot ever be null. – Chris Oct 19 '14 at 14:29
  • @Chris my bad, didn't notice that! I normally use `(int)`. I'll update my answer – DividedByZero Oct 19 '14 at 14:33
  • Just noticed also that you said "`(int)string` will return an exception" whereas I think its actually a compile time error... – Chris Oct 19 '14 at 14:42