Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

keyword

From the docs:

The as operator is like a cast except that it yields null on conversion failure instead of raising an exception. More formally, an expression of the form:

   expression as type 

is equivalent to:

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

except that expression is evaluated only once.

So why wouldn't you choose to either do it one way or the other. Why have two systems of casting?

like image 899
patrick Avatar asked Jul 01 '10 17:07

patrick


People also ask

What is the purpose of as operator?

The as operator is used to perform conversion between compatible reference types or Nullable types. This operator returns the object when they are compatible with the given type and return null if the conversion is not possible instead of raising an exception.

What is the purpose of as operator in C sharp?

The As operator in C# is used to convert from one type to another. You can use casting to cast one type to another but if you apply casting on incompatible types, you will get an exception. The As operator in C# is used to convert from one type to another.

What is the difference between IS and AS?

Differences Between As and IsThe is operator returns true if the given object is of the same type, whereas the as operator returns the object when they are compatible with the given type.

What is new in C sharp?

Use the new keyword to create an instance of the array. The new operator is used to create an object or instantiate an object. Here in the example an object is created for the class using the new.


1 Answers

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/

like image 100
Eric Lippert Avatar answered Oct 11 '22 21:10

Eric Lippert