Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Direct casting vs 'as' operator?

Tags:

c#

casting

Consider the following code:

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 } 

What is the difference between the three types of casting (okay, the 3rd one is not a casting, but you get the intent). Which one should be preferred?

like image 229
nullDev Avatar asked Sep 25 '08 10:09

nullDev


People also ask

Is a cast operator in C#?

The operator used to perform cast operation in C# is parentheses. To perform a cast operation, the destination data type is explicitly written in parentheses before the value to be converted. An example for cast operation can be the conversion of a variable of double or float type to an integer type.

What does as do in C#?

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 type casting in c3?

Type casting is when you assign a value of one data type to another type. In C#, there are two types of casting: Implicit Casting (automatically) - converting a smaller type to a larger type size. char -> int -> long -> float -> double. Explicit Casting (manually) - converting a larger type to a smaller size type.

What is implicit and explicit cast in net?

Implicit conversion is the conversion in which a derived class is converted into a base class like int into a float type. Explicit conversion is the conversion that may cause data loss. Explicit conversion converts the base class into the derived class.


1 Answers

string s = (string)o; // 1 

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

string s = o as string; // 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.

string s = o.ToString(); // 3 

Causes a NullReferenceException if 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.

like image 114
Sander Avatar answered Oct 23 '22 10:10

Sander