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:
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?).
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.