Click here to Skip to main content
15,886,541 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
Dear friends,
I have come across this snippet of code while learning ASP.NET.
I am unable to comprehend it.

Please explain in simple words about its objective.

C#
public int ID
{
     get { return (ViewState["ID"] == null) ? 0 : Convert.ToInt32(ViewState["ID"]); }
     set { ViewState["ID"] = value; }
}
Posted
Updated 28-May-10 2:32am
v3

touseef4pk wrote:
get { return (ViewState["ID"] == null) ? 0 : Convert.ToInt32(ViewState["ID"]); }


This checks if ID value is stored in Viewstate or not. If it is saved then it is retrieved from Viewstate and sent across. If not stored in a viewstate then ID value returned would be 0.


touseef4pk wrote:
set { ViewState["ID"] = value; }


This sets the ID value tried to be set in a Viewstate. Thus, in future when you try to retrieve the value of ID, it checks the viewstate and send the value stored in it.


touseef4pk wrote:
public int ID


A public property ID is exposed on the page that has both get & set in it. Thus values can be retrieved and set using this ID property exposed.
 
Share this answer
 
Sandeep has explained everything very nicely.

I believe that you are finding following code more confusing.

return  (ViewState["ID"] == null) ? 0 : Convert.ToInt32(ViewState["ID"]);


In this code ?: operator has been used you can read more about this at following link.

http://msdn.microsoft.com/en-us/library/ty67wk28(VS.80).aspx[^]


Following is the simplified code for the same.

if (ViewState["ID"] == null)
        {
            return 0;
        }
        else
        {
            return Convert.ToInt32(ViewState["ID"]);
        }
 
Share this answer
 
v2
ok there is syntax (if Condition true doing 1 if not doing 2) ? (2):(1);
if value of id == null then converting to int32 and return it if not return 0;
in second line we say how set the value of viewstate
if want know some more ,read about property
 
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