Share via


Cannot implicitly convert type 'object' to 'bool'

Question

Wednesday, May 2, 2007 2:09 PM

Hi,

I am new to C#. I am trying write a code to prevent repeated submission of form.

at page load. i have written:

protected void Page_Load(object sender, EventArgs e)

{

if (!IsPostBack)

{

Session["NewForm"] =true;

}

 

And at  button click:

if (Session["NewForm"]=true )

{

//insert data to database

int comid = ComplaintInfo.Insertinfo(complaintListTable);

string srt = comid.ToString();

this.Master.DisplayMessage("Your Record is successfully submitted. Your Complaint ID is " + srt);

Session["NewForm"] = false;

}

When i run ths i get error mesage: Cannot implicitly convert type 'object' to 'bool'. An explicit conversion exists (are you missing a cast?) 

I am using VS 2005

Please help me...

 

All replies (5)

Wednesday, May 2, 2007 3:02 PM

Hi,

I think it's the line

 if (Session["NewForm"] = true )

in button click , it should be

if(Session["NewForm"] == true )

(Notice == instead of =, as == is used in C# for equality comparison)


Wednesday, May 2, 2007 3:55 PM

It also requires a cast.

// Does null check, type check and comparison
if ( Session["NewForm"] is bool && (bool)Session["NewForm"] == true )
{
    // ...
}

/* Similar, but not the same (can use this if you always know it will
    contain a bool value--this does no type check until the cast,
    which could cause an Exception if it is not a bool value):

    if ( Session["NewForm"] != null && (bool)Session["NewForm"] == true )
    {
        // ...
    }

*/

joteke is right though about the error.


Thursday, May 3, 2007 10:43 AM

Yeah I tried this 

 if ( Session["NewForm"] is bool && (bool)Session["NewForm"] == true )
 This really works .

Thanks.


Thursday, May 3, 2007 10:47 AM

I tried this

if(Session["NewForm"] == true ),

but this gives error; Operator '==' cannot be applied to operands of type 'object' and 'bool'.

Thanks. 


Thursday, May 3, 2007 11:08 AM

Ah, yeah, my bad. It needs to be casted yeah.

bool b=(bool)Session["NewForm"];
if(b){//Do something when b is true}