Home
Map
as: Cast ExamplesUse the as-cast. This cast helps with converting reference types.
C#
This page was last reviewed on Jul 4, 2023.
As-keyword. In C# programs we use "as" to cast. We gain performance and avoid exceptions when a cast is invalid. Null is returned when the cast is impossible.
Cast
For reference types, the as-cast is recommended. It is both fast and safe. We can test the resulting variable against null and then use it. This eliminates extra casts.
An example. Here we cast a string to the base object class type. Then the object variable is changed to a string with the as-operator.
Info On success, the newly-typed variable is available. In the program, variable3 is now a string.
And We can use it just like any other string, like the original variable1. There is no difference.
Important When you try an incompatible cast, such as with the StringBuilder type, the result of the casting expression is null.
null
using System; using System.Text; // Create a string variable and cast it to an object. string variable1 = "carrot"; object variable2 = variable1; // Try to cast it to a string. string variable3 = variable2 as string; if (variable3 != null) { Console.WriteLine("have string variable"); } // Try to cast it to a StringBuilder. StringBuilder variable4 = variable2 as StringBuilder; if (variable4 != null) { Console.WriteLine("have StringBuilder variable"); }
have string variable
Example 2. The as-cast will not throw an exception if the cast fails, but if you do not check its result, your program will likely fail. Here we cast an object to a List—the cast fails.
Note We try to use the null List, which causes an exception. A method cannot be called on a null instance.
null List
NullReferenceException
using System.Collections.Generic; class Program { static void Main() { string value = "cat"; object temp = value; List<string> list = temp as List<string>; list.Add("dog"); } }
Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.
Benchmark, casts. The as-cast is sometimes the most efficient cast. We can use the variable afterwards. There is seldom any reason to use an is-cast before an as-cast.
is
Version 1 In this version of the code, we test an explicit reference type cast. We cast to the StringBuilder type from an object.
Version 2 Here we use the as-cast. We convert the object reference to a StringBuilder.
Result In 2020, both casts perform about the same. So we can use whichever is clearest, or use the one with the best error handling.
using System; using System.Diagnostics; using System.Text; const int _max = 1000000000; StringBuilder builder = new StringBuilder(); object item = (object)builder; // Version 1: use cast. var s1 = Stopwatch.StartNew(); for (int i = 0; i < _max; i++) { StringBuilder build = (StringBuilder)item; if (build == null) { throw new Exception(); } } s1.Stop(); // Version 2: use as-cast. var s2 = Stopwatch.StartNew(); for (int i = 0; i < _max; i++) { StringBuilder build = item as StringBuilder; if (build == null) { throw new Exception(); } } s2.Stop(); Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns"));
0.81 ns Cast 0.81 ns As-cast
FxCop. Excessive casting is a performance complaint in the FxCop static analysis tool. Also, the as-cast avoids throwing an exception on an invalid cast, which is much faster.
Internals. Next we consider the implementation of casts. At the instruction level, you will see that the as-cast is implemented in terms of the isinst opcode, the same used for the is-cast.
However The isinst instruction is followed by further instructions. These store the local variable that was received by the ininst code.
And By storing the local variable, the as-cast results in the overall reduction of cast instructions.
Intermediate Language
A summary. With "as" we cast reference variables. This cast receives 2 operands: the variable to cast, and the type you are trying to cast to. It returns the cast variable (or null).
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jul 4, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.