Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should you use the as keyword in C#

When you want to change types most of the time you just want to use the traditional cast.

var value = (string)dictionary[key];

It's good because:

  • It’s fast
  • It’ll complain if something is wrong (instead of giving object is null exceptions)

So what is a good example for the use of as I couldn't really find or think of something that suits it perfectly?

Note: Actually I think sometimes there are cases where the complier prevents the use of a cast where as works (generics related?).

like image 905
Daniel Little Avatar asked Sep 27 '11 08:09

Daniel Little


People also ask

Why we are using keywords in C?

Keywords are predefined, reserved words in C language and each of which is associated with specific features. These words help us to use the functionality of C language. They have special meaning to the compilers.

Can we use keywords as variables in C?

Keywords are the words whose meaning has already been explained to the C compiler. They have a specific meaning and they implement specific C language features. Keywords can be used only for their intended purpose. They cannot be used as names for variables or other user-defined program elements.

Should you use this -> in C++?

While this is a totally subjective question, I think the general C++ community prefers not to have this-> . Its cluttering, and entirely not needed. Some people use it to differentiate between member variables and parameters.


Video Answer


3 Answers

Use as when it's valid for an object not to be of the type that you want, and you want to act differently if it is. For example, in somewhat pseudo-code:

foreach (Control control in foo)
{
    // Do something with every control...

    ContainerControl container = control as ContainerControl;
    if (container != null)
    {
        ApplyToChildren(container);
    }
}

Or optimization in LINQ to Objects (lots of examples like this):

public static int Count<T>(this IEnumerable<T> source)
{
    IList list = source as IList;
    if (list != null)
    {
        return list.Count;
    }
    IList<T> genericList = source as IList<T>;
    if (genericList != null)
    {
        return genericList.Count;
    }

    // Okay, we'll do things the slow way...
    int result = 0;
    using (var iterator = source.GetEnumerator())
    {
        while (iterator.MoveNext())
        {
            result++;
        }
    }
    return result;
}

So using as is like an is + a cast. It's almost always used with a nullity check afterwards, as per the above examples.

like image 150
Jon Skeet Avatar answered Oct 28 '22 16:10

Jon Skeet


Every time when you need to safe cast object without exception use as:

MyType a = (MyType)myObj; // throws an exception if type wrong

MyType a = myObj as MyType; // return null if type wrong
like image 20
Samich Avatar answered Oct 28 '22 16:10

Samich


As is used to avoid double casting logic like in:

if (x is MyClass)
{
  MyClass y = (MyClass)x;
}

Using

MyClass y = x as MyClass;
if (y == null)
{
}

FYI, IL generated for case #1:

  // if (x is MyClass)
  IL_0008:  isinst     MyClass
  IL_000d:  ldnull
  IL_000e:  cgt.un
  IL_0010:  ldc.i4.0
  IL_0011:  ceq
  IL_0013:  stloc.2
  IL_0014:  ldloc.2
  IL_0015:  brtrue.s   IL_0020
  IL_0017:  nop
  // MyClass y = (MyClass)x;
  IL_0018:  ldloc.0
  IL_0019:  castclass  MyClass
  IL_001e:  stloc.1

and for case #2:

  // MyClass y = x as MyClass;
  IL_0008:  isinst     MyClass
  IL_000d:  stloc.1
  // if (y == null)
  IL_000e:  ldloc.1
  IL_000f:  ldnull
  IL_0010:  ceq
  IL_0012:  stloc.2
  IL_0013:  ldloc.2
  IL_0014:  brtrue.s   IL_0018
like image 9
vc 74 Avatar answered Oct 28 '22 16:10

vc 74