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?
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.
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.
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.
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.
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
Why not try it?
You get a null value, no exception. Actually, the point of as
is to never throw an exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With