What's the difference between "as" and "cast" operators? [Resolved]

Posted by krrishbiju-15589 under C# on 9/2/2013 | Points: 10 | Views : 1071 | Status : [Member] | Replies : 5
Hi,

What's the difference between "as" and "cast" operators in c#?
Regards
krrishbiju




Responses

Posted by: Bandi on: 9/2/2013 [Member] [MVP] Platinum | Points: 50

Up
0
Down

Resolved
Performing an explicit cast differs from using the as operator in three major aspects.
The as operator…
1) returns a null if the variable being converted is not of the requested type nor present in its inheritance chain. On the other hand, a cast would throw an exception.
2) can be applied only to reference type variables being converted to reference types.
3) cannot perform user-defined conversions—e.g., explicit or implicit conversion operators. A cast could perform these types of conversions.
Far from being merely cosmetic, the as operator and casting are handled by two seperate operations defined in Intermediate Language (IL)—the castclass and isinst IL instructions.

String text = "Hello hello";

Object obj = text;

String originalCast = ((String)obj).ToUpper();
String originalAs = (obj as String).ToUpper();

as will never throw a InvalidCastException. Instead, it returns null if the cast fails (which will give you a NullReferenceException for the above code)

Refer this link
http://gen5.info/q/2008/06/13/prefix-casting-versus-as-casting-in-c/

Mark This Response as Answer
--
Chandu
http://www.dotnetfunda.com/images/dnfmvp.gif

krrishbiju-15589, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Bandi on: 9/2/2013 [Member] [MVP] Platinum | Points: 25

Up
0
Down
// I swear o is a string

string s = (string)o; // 1
//-OR-
string s = o as string; // 2
// -OR-
string s = o.ToString(); // 3


1) Throws InvalidCastException if o is not a string. Otherwise, assigns o to s, even if o is null. 

2) Assigns null to s if o is not a string or if o is null. For this reason, you cannot use it with value types (the operator could never return null in that case). Otherwise, assigns o to s.
3) Causes a NullReferenceException of o is null. Assigns whatever o.ToString() returns to s, no matter what type o is.


Use 1 for most conversions - it's simple and straightforward.
I tend to almost never use 2 since if something is not the right type, I usually expect an exception to occur. I have only seen a need for this return-null type of functionality with badly designed libraries which use error codes (e.g. return null = error, instead of using exceptions).
3 is not a cast and is just a method invocation. Use it for when you need the string representation of a non-string object.


Mark This Response as Answer
--
Chandu
http://www.dotnetfunda.com/images/dnfmvp.gif

krrishbiju-15589, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Allemahesh on: 9/2/2013 [Member] [MVP] Silver | Points: 25

Up
0
Down
Below are some differences of Direct casting vs 'as' operator?:-

See the below examples:-

void Handler(object o, EventArgs e)
{
// I swear o is a string
string s = (string)o; // 1
//-OR-
string s = o as string; // 2
// -OR-
string s = o.ToString(); // 3 3rd one is not a casting, but you get the an idea.
}


Below are line wise different:-

1. Throws InvalidCastException if o is not a string. Otherwise, assigns o to s, even if o is null.
2. Assigns null to s if o is not a string or if o is null. For this reason, you cannot use it with value types (the operator could never return null in that case). Otherwise, assigns o to s.
3. Causes a NullReferenceException of o is null. Assigns whatever o.ToString() returns to s, no matter what type o is.

Happy coding.

krrishbiju-15589, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Allemahesh on: 9/2/2013 [Member] [MVP] Silver | Points: 25

Up
0
Down
Using the as operator differs from a cast in C# in three important ways:

It returns null when the variable you are trying to convert is not of the requested type or in it's inheritance chain, instead of throwing an exception.
It can only be applied to reference type variables converting to reference types.
Using as will not perform user-defined conversions, such as implicit or explicit conversion operators, which casting syntax will do.
There are in fact two completely different operations defined in IL that handle these two keywords (the castclass and isinst instructions) - it's not just "syntactic sugar" written by C# to get this different behavior. The as operator appears to be slightly faster in v1.0 and v1.1 of Microsoft's CLR compared to casting (even in cases where there are no invalid casts which would severely lower casting's performance due to exceptions).

Happy coding.

krrishbiju-15589, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Satyapriyanayak on: 9/2/2013 [Member] [MVP] Silver | Points: 25

Up
0
Down
http://tutorials.csharp-online.net/CSharp_FAQ%3A_What_is_the_difference_between_using_a_cast_and_the_as_operator

If this post helps you mark it as answer
Thanks

krrishbiju-15589, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response