Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the result of using the "as operator" on a null object?

Tags:

c#

C# has the as keyword which can cast an object into something else, or fail and return null if it doesn't work.

What happens if the value I try to as cast is null already? Do I get null out or does it throw some exception?

like image 331
tomjen Avatar asked Jul 13 '14 19:07

tomjen


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 type of operator is is null?

The null coalescing operator (called the Logical Defined-Or operator in Perl) is a binary operator that is part of the syntax for a basic conditional expression in several programming languages, including C#, PowerShell as of version 7.0.

How do you use the null operator?

operator is known as Null-coalescing operator. It will return the value of its left-hand operand if it is not null. If it is null, then it will evaluate the right-hand operand and returns its result. Or if the left-hand operand evaluates to non-null, then it does not evaluate its right-hand operand.


2 Answers

It would return null. The as operator's purpose is to avoid throwing an exception, per MSDN:

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

For example:

object o = null; // also try with a string type
string result = o as string;
Console.WriteLine(result); // null
like image 57
Ahmad Mageed Avatar answered Sep 20 '22 07:09

Ahmad Mageed


Why not try it?

You get a null value, no exception. Actually, the point of as is to never throw an exception.

like image 33
dcastro Avatar answered Sep 18 '22 07:09

dcastro