Comparison between them and cast

Possible duplicate:
Direct casting vs 'how' operator?

Can anyone give a comparison between as and cast?

+3
source share
3 answers

A direct throw will not work if the object to which the spell is cast does not match the requested type. Instead of as-cast, null is returned instead. For instance:

object obj = new object();
string str = (string)obj; // Throws ClassCastException

However:

object obj = new object();
string str = obj as string; // Sets str to null

When the object being thrown is of the type that you are executing, the result will be the same for any syntax: the object succeeded.

Note that you should avoid the as-and-call pattern:

(something as SomeType).Foo();

, , NullReferenceException ClassCastException. , something NULL, ! ,

((SomeType)something).Foo();

ClassCastException, , something, SomeType, NullReferenceException, something null.

+11

"" null, .

:

if (objectForCasting is CastingType)
{
   result = (CastingType)objectForCasting;
}
else
{
   result = null;
}

null :

CastingType resultVar = sourceVar as CastingType;

if (resultVar == null)
{
   //Handle null result here...
}
else
{
   // Do smth with resultVar...
}
+1

as .

as...

  • returns null if the transformed variable is not of the requested type and is not present in the inheritance chain. On the other hand, the throw will throw an exception.
  • can only be applied to variables of a reference type that are converted to reference types.
  • cannot perform custom transformations, for example, explicit or implicit conversion operators. Listing can perform these types of conversions.
0
source

Source: https://habr.com/ru/post/1775123/


All Articles