Click to See Complete Forum and Search --> : Session Variable & C# Casting


rachacko
July 24th, 2003, 11:19 AM
I am new to Asp world and I have a doubt as follows. I
have a class called objTranslator, which I declare and
initiate global.asax as follows.

In Session_Start

csTranslator.objTranslator sesObjTranslator= new
objTranslator();
Session["sesTranslator"]=sesObjTranslator;
----------------
In WebForm

private csTranslator.objTranslator webTranslator;

In Page Load

if(Session["sesTranslator"]!=null)
webTranslator=(objTranslator)Session["sesTranslator"];

The question is why do I have to explictly cast the
session variable sesTransilator to objTransilator while it
is holding a reference to sesObjTranslator.

So actually what type is the session variable.

In VB.Net one can directly use

webTranslator=Session("sesTranslator")

What is the difference here?

Thanks,

Rajesh Abraham Chacko

coolbiz
July 24th, 2003, 02:07 PM
C# is like C/C++, they are strongly-typed. Session variable is typed as OBJECT and therefore has to be cast to the right type. VB still inherits its predecessor versions where variables can be loosely typed and therefore does not require casting.

You can change this option so that VB will behave like C#. At the top of your file type in "Option Strict On" or from your project properties, go to BUILD option and change the OPTION STRICT to ON (this will make the option effective on the whole project so that you don't have to declare it at the beginning of each files).

The recommendation is to always turn this option on.

-Cool Bizs