Object Types in Application & Session

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Let's say I store a real simple value in the Session as follows
Session["MyName"] = "Alex"

Later, in a different page, I try to do something like
SomeLabel.Text = Session["MyName"]

When I do this, I get a compilation error "CS0029: Cannot implicitly convert type 'object' to 'string'

Is this because an object of any type *could* be stored in there and the compiler insists that I tell it in advance? If so, is this true for any Collection

Alex
 
no because its because somelabel.Text is of type String and
Session["MyName"] is of type object ...

and compiler is saying that its application's responsibility to convert
it into correct Type before assignment

remember in the statement
Session["MyName"] = "Alex";

compiler knows that "Alex" is a literal of type String

hth
-ashish
 
yes. most general purpose collections (like Session) return an object. if
you know the type you can cast it

SomeLabel.Text = (string) Session["MyName"];

note: this will thow an error if the object is not a string.

c# is strongly typed language and requires the types of an assignment be the
compatible at compile time.

-- bruce (sqlwork.com)


Alex Maghen said:
Let's say I store a real simple value in the Session as follows:
Session["MyName"] = "Alex";

Later, in a different page, I try to do something like:
SomeLabel.Text = Session["MyName"];

When I do this, I get a compilation error "CS0029: Cannot implicitly
convert type 'object' to 'string'"
Is this because an object of any type *could* be stored in there and the
compiler insists that I tell it in advance? If so, is this true for any
Collection?
 
Back
Top