Not a subscriber?

Join thousands of others who are building self-directed lives through creativity, grit, and digital strategy—breaking free from the 9–5.
Receive one free message a week

The “as” Keyword

Last week I ran into a problem with the ‘as’ keyword in C#. For those of you who dont know, the “as” keyword works like this:

Lets say I have a variable and I’m certain its a string, but its in the form of an object (for whatever weird reason, perhaps you’re getting it out of an ArrayList or something). I want to cast it to string. I can use the “as” keyword to do this.

string stuff = objectVariable as string;

So I had a problem this week when a co-worker wrote some code that did the following:

// Get variable from session
string myId = Session[“objectKey”] as string;

Each time I accessed this variable (myId) it was null. WTF? I debugged for a second and I verfied that it was being set like so:

// Save Id for later
Session[“objectKey”] = theIdToSave;

The variable “theIdToSave” was set to, lets say, a number, 5. Session saves everything as an object. The “as” keyword is a shorthand version of the tenary operator,  therefore…

string stuff = objectVariable as string;

//Is the same as

objectVariable is string ? (string)objectVariable : (string)null;


The problem was that we were putting a Int32 type into an object and trying to cast it to a string. This will only work if, and only if, it was of type string. Unfortunately it was not a string, it was of type Int32. Thefore, instead of raising an exception, the “as” keyword returns a null value. The type of the object in session can be verified by reflecting into the object by using the GetType method.

// This will return: {Name = “Int32” FullName = “System.Int32”}    
Session[“Test”].GetType();

Keep in mind, when working with the “as” keyword in C#, be sure to know what types your working with. If you’re trying to cast a variable to a type that it is not of, the “as” keyword will internally yield a null value instead of raising an exception.