Reputation: 63
Class is derived from Control in Asp.Net C#.
Public class member is defined as:
public bool isPresent = true;
Then in Render method check is performed :
if (isPresent)
doSomething;
On a form this field is set to false:
<c:CustomControl id="CustomControl1" isPresent="false">
When this code is executed locally from VS, everything is fine. Being deployed to the server, however, throws exception for the line with check for "if (isPresent)", saying that object reference is not set.
At the same time, if this line is changed to be "if (isPresent == true)", everything is fine both locally and on the server.
Is setting of value for class member of the Control different when run from VS and from IIS? Is it initialized in IIS before comparison operation, and not before implicit check?
UPDATE: as has been correctly pointed, this variable is a field, not a property. There is no other class member (and no property with same name).
UPDATE2: in addition, if check for value being not null is added, there is no exception anymore. Can it be the case that object initializer sets value of the field in case of explicit comparison operation?
if (isPresent == null)
return;
if (isPresent)
doSomething;
Upvotes: 1
Views: 551
Reputation: 3449
When creating user controls, the most advisable manner to store property values is in the View State, as follows:
public bool IsPresent
{
get
{
bool isPresent = false;
if (ViewState["IsPresent"] != null)
{
isPresent = (bool) ViewState["IsPresent"];
}
return isPresent;
}
set
{
ViewState["IsPresent"] = value;
}
}
Then, the control would be declared as follows (Note that the IsPresent starts with Upper I):
<c:CustomControl id="CustomControl1" IsPresent="false">
Whenever storing data on controls, keep in mind that they must be persisted on the page. If you simply declare a variable, there is no guarantee that the data will hold between requests. The only manner to make sure the data is persisted, is to save it in the View State. You can find support to these statements here and here.
The question of why the behavior changes in the IIS and Visual Studio may be not relevant here because simply declaring a variable, as stated above, provides no assurance at all that the data will be saved.
Regarding the Property being a getter/setter, note that it must be declared as shown above, in order to the property to be recognized by the ASPX page.
Upvotes: 1