Click here to Skip to main content
15,921,156 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have a error that shows: Operator '!' cannot be applied to operand of type object in my following code. How do i solve it?

C#
if (!(Session["counter"]))
        {
            counter = (int)Session["counter"];
        }
Posted

Try this.

C#
(! (Session["Counter"] is null)
counter = (int)Session["counter"];
 
Share this answer
 
As MSDN[^] states:

The logical negation operator (!) is a unary operator that negates its operand. It is defined for bool and returns true if and only if its operand is false.


hence you cannot apply it to integer variables.

You might change it to:
C#
if ( Session["counter"] != 0)
{
//...
}
 
Share this answer
 
Comments
kellycx 24-Jul-12 12:54pm    
I changed the codes to the one you suggested but it still return me the same error. Is it because i declared it in my Page Load already?

This is my .cs code for Page Load:

protected void Page_Load(object sender, EventArgs e)
{
if (!(Page.IsPostBack))
{
Session["counter"] = null;
}
}
Sergey Alexandrovich Kryukov 24-Jul-12 14:30pm    
No!! Read the answer by CPallini again. Can you read?
--SA
Sergey Alexandrovich Kryukov 24-Jul-12 14:30pm    
Sure, a 5.
--SA
CPallini 24-Jul-12 15:58pm    
Thank you very much Sergey Alexandr... Well, SA!
:-)
kellycx 25-Jul-12 3:12am    
I think you dun understand what i am saying. It's OK i solved it myself already
It depends on the value of the session variable Counter.

If you are assuming it is a integer value, you should be writing code like
if (!(int)Session["counter"] == 0)
{
  counter = ....
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900