Rod
Rod

Reputation: 15455

session in a property field

Is it ok to get/set session variable inside a private/public property?

private List<FileAttachment> fileAttachments;
public List<FileAttachment> FileAttachments
{
    get
    {
        if (Session["key"] != null)
        {
            fileAttachments = (List<FileAttachment>)Session["key"];
        }
        return fileAttachments;
    }
    set
    {
        fileAttachments = value;
        Session["key"] = fileAttachments;
    }
}

The goal here is I'd like for the container class (of this user control the property is in) to be able to set the List<T> depending on what entity and show existing attachments that's stored in the database.

Upvotes: 0

Views: 49

Answers (1)

SLaks
SLaks

Reputation: 887451

That's not very safe; List<T> is not thread-safe.

You can never modify the list after assigning it to the property, since some other request thread might be reading it.

Therefore, you should make it a ReadOnlyCollection<T> rather than List<T>.
(and make sure your FileAttachment class is immutable or thread-safe)


Other than that, it depends where the property is.
If it's on a control or page, it's fine.

Upvotes: 1

Related Questions