0

In C# it is possible to cast variables using the following two syntaxes:

(Type)name or name as Type

I have looked around online and can't seem to find an answer, is there any fundamental difference in these two methods and, if not, why are both available (i.e. are there some cases where one would be more appropriate than the other).

ScottishTapWater
  • 3,656
  • 4
  • 38
  • 81
  • 1
    IIRC, the basic difference is that `(Type) name` will throw an exception if `name` cannot be cast to `Type`, but `name as Type` will return null instead. – vbnet3d Dec 21 '16 at 16:33
  • 1
    See also: http://stackoverflow.com/questions/4926677/c-sharp-as-cast-vs-classic-cast, http://stackoverflow.com/questions/6400925/c-sharp-different-ways-of-casting-tobj-vs-obj-as-t, http://stackoverflow.com/questions/13649501/c-sharp-as-vs-conversion (I bet this is in the MSDN documentation, too...) – Cody Gray - on strike Dec 21 '16 at 16:33
  • Thanks @CodyGray I must have been searching for the wrong thing. – ScottishTapWater Dec 21 '16 at 16:37
  • I literally searched for "as cast c#". The parenthetical cast syntax would admittedly be difficult to search for. – Cody Gray - on strike Dec 21 '16 at 16:38

0 Answers0