What's the point of “As” keyword in C#

后端 未结 7 1209
误落风尘
误落风尘 2020-12-13 01:32

From the docs:

The as operator is like a cast except that it yields null on conversion failure instead of raising an exception. More formally, an exp

7条回答
  •  旧巷少年郎
    2020-12-13 02:18

    Efficiency and Performance

    Part of performing a cast is some integrated type-checking; so prefixing the actual cast with an explicit type-check is redundant (the type-check occurs twice). Using the as keyword ensures only one type-check will be performed. You might think "but it has to do a null check instead of a second type-check", but null-checking is very efficient and performant compared to type-checking.

    if (x is SomeType )
    {
      SomeType y = (SomeType )x;
      // Do something
    }
    

    makes 2x checks, whereas

    SomeType y = x as SomeType;
    if (y != null)
    {
      // Do something
    }
    

    makes 1x -- the null check is very cheap compared to a type-check.

提交回复
热议问题