Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is difference between normal typecasting and using “AS” keyword [duplicate]

Tags:

c#

.net

Possible Duplicates:
Direct casting vs 'as' operator?
Casting: (NewType) vs. Object as NewType

What is difference between normal typecasting and using “AS” keyword?

like image 545
Ram Avatar asked Sep 16 '10 05:09

Ram


People also ask

What is difference between IS and AS?

The is operator returns true if the given object is of the same type whereas as operator returns the object when they are compatible with the given type. The is operator returns false if the given object is not of the same type whereas as operator return null if the conversion is not possible.

How is the as keyword used How is it different from casting?

The as operator can only be used on reference types, it cannot be overloaded, and it will return null if the operation fails. It will never throw an exception. Casting can be used on any compatible types, it can be overloaded, and it will throw an exception if the operation fails.

What is difference between casting and as C#?

Using 'as' will return null if the 'cast' fails where casting will throw an exception if the cast fails. Show activity on this post. Using 'as' will not throw an exception if the obj is not a String. Instead it'll return null.

What is typecasting and what are its types explain with suitable example?

Typecasting, or type conversion, is a method of changing an entity from one data type to another. It is used in computer programming to ensure variables are correctly processed by a function. An example of typecasting is converting an integer to a string.


1 Answers

Using as will fail gracefully if the object is the wrong type, and the resulting value will be null, where a normal cast would throw an InvalidCastException:

object x = new object();
string y = x as string; // y == null
string z = (string)x; // InvalidCastException
like image 147
Bennor McCarthy Avatar answered Nov 12 '22 11:11

Bennor McCarthy