Which code is better: use "as" or "eat"?

Possible duplicate:
Casting against the 'as' keyword in C # CLR
: "is" vs "as"

This code:

    if (sheet.Models.Data is GroupDataModel)
    {
        GroupDataModel gdm = (GroupDataModel)sheet.Models.Data;

and this code:

    GroupDataModel gdm = sheet.Models.Data as GroupDataModel;
    if (gdm != null)
    {

Do you recommend either of the two styles over the other?

+1
source share
5 answers

I think this is better because it is being converted, and also you can easily check .. the second is good

More on this: Implicit and explicit casting of an object and the role of the keyword 'is' and 'as' in explicit casting

The difference between as and

  • Null, . , .

  • . false, . , .

+3

FxCop, (as)

+5

.

. , ( is, ).

+1

, IL:

void Main() {
    Class1 inst1 = new Class1();
    ((inst1 as Class1) != null).Dump();

    Class1 inst2 = new Class1();
    (inst2 is Class1).Dump();
}

class Class1 { }

IL

IL_0001:  newobj      UserQuery+Class1..ctor
IL_0006:  stloc.0     
IL_0007:  ldloc.0     
IL_0008:  ldnull      
IL_0009:  ceq         
IL_000B:  ldc.i4.0    
IL_000C:  ceq         
IL_000E:  call        LINQPad.Extensions.Dump
IL_0013:  pop         
IL_0014:  newobj      UserQuery+Class1..ctor
IL_0019:  stloc.1     
IL_001A:  ldloc.1     
IL_001B:  ldnull      
IL_001C:  ceq         
IL_001E:  ldc.i4.0    
IL_001F:  ceq         
IL_0021:  call        LINQPad.Extensions.Dump

Class1..ctor:
IL_0000:  ldarg.0     
IL_0001:  call        System.Object..ctor
IL_0006:  ret   
+1

If you intend to use a printed object, use " as".

If you are not going to use the object with the type itself, use " is".

This is another problem if you EXPECT these objects of one type or another. Then just use the throw and let it throw an exception if the type does not match what was expected.

+1
source

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


All Articles