Tip. Getting object from session.

Tip. Getting object from session.

Old forum URL: forums.lhotka.net/forums/t/2518.aspx


tetranz posted on Tuesday, March 13, 2007

I know this is hardly an earth shaking revelation but for what its worth ... the "as" keyword in C# is quite useful and easily forgotten. I'm starting my first serious web app with CSLA and following ProjectTracker I notice this on most pages ...

object businessObject = Session["currentObject"];
if (businessObject == null || !(businessObject is Project))
{
    ...
}

The following works nicely and takes care of both situations of the session object not existing or is the wrong type. If it exists then you don't need to cast it again from object.

Project project = Session["currentObject"] as Project

if (project == null)
{
    ...
}

Ross

RRorije replied on Wednesday, March 14, 2007

Nice, I have seen the 'as' keyword a number of times now in different C# examples. Yet I did not know what it meant and that I should sort that out the next time I would com across it. Which I obviously hadn't done untill now.

So thanks.

burmajam replied on Wednesday, March 14, 2007

I do agrea with you. As it name says, "as" is safe type caster.

Copyright (c) Marimer LLC