views:

244

answers:

3

I'm on an ASP.Net 2.0 project, in C#. I have some data that gets stored in session state. For ease of use, it is wrapped in a property, like this:

protected IList<Stuff> RelevantSessionData
{
    get
    {
        return (IList<Stuff>) Session["relevant_key"];
    }
    set
    {
        Session["relevant_key"] = value;
    }
}

Getting and setting the value works exactly as you'd expect. If I want to clear the value, I just set it to null, and there are no problems. However, in another developer's page, he calls the collection's Clear() method. I thought this would be a bug, but it seems to work, and I don't understand why. It works like so:

Debug.WriteLine(RelevantSessionData.Count);    //outputs, say, 3
RelevantSessionData.Clear();
Debug.WriteLine(RelevantSessionData.Count);    //outputs 0

Why does this work? My naive expectation would be that the middle line loads the serialized value from session, deserializes into an object, calls Clear() on that object, and then lets the unnamed object fall out of scope. That would be a bug, because the value stored in Session would remain unchanged. But apparently, it's smart enough to instead call the property setter and serialize the newly changed collection back into session.

This makes me a little nervous, because there are places in our legacy code where property setters have side effects, and I don't want those getting called if it's not intended.

Does the property setter always get called in a situation like this? Is something else going on? Or do I completely misunderstand what's happening here?

[Added to explain answer]
It turns out did misunderstand. I knew that objects stored in Session must be serializable, and based on that I made too many assumptions about how the collection behaves internally. I was overthinking.

There is only one instance of the stored object (my IList). Each call to the getter returns a reference to that same instance. So the quoted code above works just as it appears, with no special magic required.

And to answer the title question: No, setters are not called implicitly.

+3  A: 

Yes, you are right, this would be a bug if your setter/getters were serializing/deserializing the objects. But this is not the case. Instead you are passing based on reference.

So what's basically happening is that the first line in your example gets the item via the get, and Count is called based on that. Then the seccond line is going out and calling get again, returning the same object, running clear, and then the third line is doing the same as the first.

If you had written your setter/getter something like this, you would have a "bug"

protected IList<Stuff> RelevantSessionData
{
    get
    {
        return (IList<Stuff>) JSON.ConvertFromString(Session["relevant_key"]);
    }
    set
    {
        Session["relevant_key"] = JSON.ConvertToString(value);
    }
}

In this case, a new object would be created and for each call to the get block. But since your example above is simply passing around the reference to the same object, you're not going to see this "bug".

And I say "bug" since it's not really a bug, it's just more of a misunderstanding of what's happening behind the scenes.

I hope this helps.

Timothy Baldridge
Aha! I had assumed that because values in Session must be serializable, they would be stored in serialized state, and each get would return a different reference. If that's not the case, and it's smart enough to return the same reference on multiple calls, then I was just overthinking it.
Auraseer
+1  A: 

Your code is roughly equivalent to:

Debug.WriteLine(((IList<Stuff>) Session["relevant_key"]).Count);    //outputs, say, 3
((IList<Stuff>) Session["relevant_key"]).Clear();
Debug.WriteLine(((IList<Stuff>) Session["relevant_key"]).Count);    //outputs 0

Even if you only call the getter, you are clearing the collection. So the debug output seems normal.

Laurent Etiemble
+1. In fact, best practice for colletion properties is to make them readonly (no setter at all).
Joel Coehoorn
I think you missed my point. I know what the property accessor does, but my error was in assuming that HttpSessionState serializes/deserializes on every access.
Auraseer
I missed the serialization/de-serialization part. I should have read the question more carefully.
Laurent Etiemble
A: 

You can expect property setters to be called if:

  • The are publicly visible (visible to other assemblies).
  • They implement the setter as part of an interface visible to other assemblies. In some cases, such as
  • They are used in WPF binding (but the framework will follow the rules about the BindingMode).
  • They are used in MEF with the ImportAttribute.
  • They are used in some other binding framework (you get the idea).

You shouldn't run into problems if, for interfaces defined by others, you meet the pre- and post-conditions of the operation.

Edit: I agree with the above. My first choice for exposing a collection is:

private readonly List<T> _sources = new List<T>();

/* Or ICollection<T>, ReadOnlyCollection<T>, or IList<T>, or
 * (only a real option for `internal` types) List<T>
 */
public IEnumerable<T> Sources
{
    get
    {
        return _sources;
    }
}

If you absolutely must initialize the list after the object is created, then you can use something like this as the second option:

public IList<T> Sources
{
    get;
    private set;
}

There are situations where the above practices aren't necessarily the best answer, but these are the two most common (IMO?).

280Z28
-1, answer is completely off the topic of the original post. OP asked why the given code was working, and if he could expect a bug due to the object being re-created.
Timothy Baldridge