-4

In C# What's the difference in casting if I do

MyType  mytype = (MyType) obj;

Or

MyType  mytype = obj as MyType;
Harshana Narangoda
  • 775
  • 1
  • 8
  • 23
Ahmed
  • 14,503
  • 22
  • 92
  • 150
  • 4
    [Here is the same question with an excellent answer](http://stackoverflow.com/questions/496096/casting-vs-using-the-as-keyword-in-the-clr) – germi Apr 25 '14 at 10:35

2 Answers2

1

The first methods fails when obj cannot be converted into MyType. When you use the second way then mytype is eitherobj casted into MyType or it is null if it cannot be casted.

zimmerrol
  • 4,872
  • 3
  • 22
  • 41
0

The second one can only be used with reference types (classes and interfaces) and will return null if the variable is not of the cast type. The first works with any types (structs as well) and will instead throw an exception.

Ricardo Peres
  • 13,724
  • 5
  • 57
  • 74