As
-keywordIn 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.
Here we cast a string
to the base object class
type. Then the object variable is changed to a string
with the as
-operator.
string
.StringBuilder
type, the result of the casting expression is 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
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.
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
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.
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
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.
StringBuilder
type from an object.as
-cast. We convert the object reference to a StringBuilder
.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
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
).