0

What is the difference between the two types of casts available in c#?

Specifically, what is the difference between. (int)7.6 and 7.6 as int and similar casts?

J S
  • 23
  • 3
  • `7.6 as int` won't compile because the `as` operator returns `null` if the cast it not possible. Since `null` cannot be assigned to an `int`, the code will not compile. – Wai Ha Lee Jul 26 '16 at 16:27

2 Answers2

0

as will return null if it can't convert to the given type. Casting will throw an exception

SimonPJ
  • 756
  • 9
  • 21
0

The as operator is like a cast operation. However, if the conversion isn't possible, as returns null.

if you use an implicit cast and the cast is not possible you will get an exception.

lem2802
  • 1,152
  • 7
  • 18