Home
C#
as: Cast Examples
This page was last reviewed on Sep 21, 2024.
Dot Net Perls
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.
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.
is
Cast
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.
Part 1 On success, the newly-typed variable is available. In the program, the variable "s" is now a string.
Part 2 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; string c = "carrot"; object o = c; // Part 1: try to cast the object to a string. string s = o as string; if (s != null) { Console.WriteLine("have string variable"); } // Part 2: try to cast it to a StringBuilder. StringBuilder b = o as StringBuilder; if (b != null) { Console.WriteLine("have StringBuilder variable"); }
have string variable
Null. If we do not check the result of an as-cast, our program may fail due to a null reference. Here we cast an object to a List. We try to use the null value, which causes an exception.
NullReferenceException
using System.Collections.Generic; string value = "cat"; object temp = value; List<string> list = temp as List<string>; // Exception because the variable is null. list.Add("dog");
Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object. at ...\Program.cs:line 7
Is, pattern matching. In modern times we can use an "is type" pattern-matching cast in an if-statement instead of as-cast. This captures the casted variable, so we can use it within the if-block.
Tip This approach is better than an as-cast, as we can only access the cast value (here the string "e") within the block, not elsewhere.
using System; string c = "abc"; object x = c; // Use "is" pattern-matching in if-statement instead of an as-cast. if (x is string e) { Console.WriteLine("Length of string is {0}", e.Length); }
Length of string is 3
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.
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 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
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 Sep 21, 2024 (edit link).
Home
Changes
© 2007-2024 Sam Allen.