Confusion regarding C # property

I got a sample code from the site. One thing that I just don’t understand about how the value is added to ViewStateautomatically.

code as follows

private Dictionary<Guid, string> Names
{
    get { return (Dictionary<Guid, string>)ViewState["Names"]; }
    set { ViewState["Names"] = value; }
}

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        // to keep this sample really simple, we will populate some
        // sample data in a Dictionary and store in the viewstate
        var names = new Dictionary<Guid, string>
        {
            { Guid.NewGuid(), "John" },
            { Guid.NewGuid(), "Smith" },
            { Guid.NewGuid(), "Arther" },
            { Guid.NewGuid(), "Hari" }
        };
        //store the list in the viewstate.
        ViewState.Add("Names", names);

        //init grid           
    }
}

protected void btnAddSave_Click(object sender, EventArgs e)
{
    if (Page.IsValid)
    {
        Names.Add(Guid.NewGuid(), txtNewName.Text);            
    }
}

in the page load event. I understand that several values ​​have been added to the Dictionary collection, and after that the entire collection is added to the ViewState with the name "Names".

in the event, the btnAddSave_Clickcode Names.Add(Guid.NewGuid(), txtNewName.Text);again adds the name to the collection.

but I just don’t understand how a new value is added to the viewstate.

- private Dictionary<Guid, string> Names, , ViewState. , . , - , ViewState, Names.Add(Guid.NewGuid(), txtNewName.Text);.

, ViewState. , , , ViewState, - collection.i , . . , , , ViewState, . !

+3
3

ViewState - ,

  Names.Add(Guid.NewGuid(), txtNewName.Text);            

:

1- , , ViewState [ "" ].

.

private Dictionary<Guid, string> Names
{   
 **get { 
         return (Dictionary<Guid, string>)ViewState["Names"];
     }**   
 set { ViewState["Names"] = value; }}

, ,

, , , , - statebag, statebag IDictionary, ViewState , , , StateBag, Control ViewState. ViewState - Control,

+2

, ViewState, , . , .

, . , ViewState.

0

The value in Names.Add is not added (directly) to the view state. It has been added to the collection, which is already in the viewstate. As a result, when the assembly is serialized, the value added to the names will be serialized. This is a matter of understanding reference types (which are in the dictionary)

0
source

Source: https://habr.com/ru/post/1778467/


All Articles