Search code examples
c#sessionattributesautomatic-properties

Anyone tried implement C#.Auto-Property which would store value in Session?


I like using c# Auto-Property in code as I found it much more nicer. Recently got an idea how I would manage to use Auto-Property, but store the value in Session. Simply for few reason: - avoid typos in Session item name - avoid extra code - possibly for extending to other stores like ViewState, etc.

So far I am thinking the Attribute would be the best option. Just curious if someone tried this before I dig in and start implementing it.

E.g.

[Session] 
public int Id{get;set;}

instead of

public int Id{ get{return Session["Id"];} set{Session["Id"] = value;}}

Solution

  • No, you can't do this.

    Automatically implemented properties only work when the desired implementation is a "trivial" property backed by a field. That's all that's supported by the compiler. Just about the only way you can "tweak" an automatically implemented property is to set the accessibility of the getter and the setter differently.

    Now of course you could write code to automatically load the value from the session on creation and save it to the session on a particular method call - but that's not really the same thing.