What's the point of "As" keyword in C#

Solution 1:

They aren't two system of casting. The two have similar actions but very different meanings. An "as" means "I think this object might actually be of this other type; give me null if it isn't." A cast means one of two things:

  • I know for sure that this object actually is of this other type. Make it so, and if I'm wrong, crash the program.

  • I know for sure that this object is not of this other type, but that there is a well-known way of converting the value of the current type to the desired type. (For example, casting int to short.) Make it so, and if the conversion doesn't actually work, crash the program.

See my article on the subject for more details.

https://ericlippert.com/2009/10/08/whats-the-difference-between-as-and-cast-operators/

Solution 2:

Efficiency and Performance

Part of performing a cast is some integrated type-checking; so prefixing the actual cast with an explicit type-check is redundant (the type-check occurs twice). Using the as keyword ensures only one type-check will be performed. You might think "but it has to do a null check instead of a second type-check", but null-checking is very efficient and performant compared to type-checking.

if (x is SomeType )
{
  SomeType y = (SomeType )x;
  // Do something
}

makes 2x checks, whereas

SomeType y = x as SomeType;
if (y != null)
{
  // Do something
}

makes 1x -- the null check is very cheap compared to a type-check.