Gaur Puneet
Gaur Puneet

Reputation: 1

how to give session value into string without type casting

I want the value of session into string without type casting and conversion in ASP.NET.

But I want without any conversion get the value of Session["username"] into temp variable.
Example - the correct way is:

string temp;
Session["username"] = "Joy";
temp = Session["username"].ToString();

Upvotes: 0

Views: 4816

Answers (3)

Amir Popovich
Amir Popovich

Reputation: 29836

A session holds objects as values and therefore you need to cast the object into the correct type to gain the type's strength. The session value can be null, so you need to check that.

string temp;
Session["username"]="Joy";
temp=Session["username"] as string;

if you use this:

object temp = Session["username"]; // temp is just a basic object.

Another issue is, since the session holds objects, value types are "boxed" into objects.
You can't use the "as" cast when you want to case value types, so:

int intTemp;
Session["num"]= 7; // int is boxed into an object
intTemp = (int)Session["num"]; // unboxed back to int
intTemp = Session["num"] as int; // cannot be done!!!

Upvotes: 3

Jameem
Jameem

Reputation: 1838

Please try this..

temp=Session["username"] as string;

As session is an object it is necessary to type cat it to the prefered type..

Upvotes: 0

MarkO
MarkO

Reputation: 2233

Since Session is of type Object (so you can put in anything) you need to cast it back to String if you want to read it.

The preffered way of doing so is (since it may not exist in your session yet)

string temp = Session["username"] as String;
if (temp == null)
{
//Doesn't exist in Session yet, so create and add
}

Upvotes: 5

Related Questions