1

Assume, that there is an interface A and a variable 'x' of a class that implements that interface. Now I can perform these:

var a = (A) x;

Or:

var a = x as A;

I know that in the case of failure, the first statement will throw an InvalidCastException and the second will return null. But is there any other difference? Particurarly in performance?

Ryszard Dżegan
  • 24,366
  • 6
  • 38
  • 56

3 Answers3

2

By doing (A)x you are doing a cast which will definatly try and cast, if it can't cast there will be an exception.

If you use as it will either cast or be null.

However, you have all the example code you need to try this yourself so you could of potentially tried this before asking us what the code you have stated is going to do.

LukeHennerley
  • 6,344
  • 1
  • 32
  • 50
1

The first one attempts to convert immediately, the second one actually checks whether x is of type A.

animaonline
  • 3,715
  • 5
  • 30
  • 57
1

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

You can use the as operator to perform certain types of conversions between compatible reference types or nullable types.

Consider the following example:

expression as type

The code is equivalent to the following expression except that the expression variable is evaluated only one time.

expression is type ? (type)expression : (type)null

Note that the as operator performs only reference conversions, nullable conversions, and boxing conversions. The as operator can't perform other conversions, such as user-defined conversions, which should instead be performed by using cast expressions.

Refer: as (C# Reference)

Kapil Khandelwal
  • 15,958
  • 2
  • 45
  • 52