Sunday, April 11, 2010

Serialization or Serializable in asp.net


  • To put a custom object into ViewState in asp.net, the class have to be declared as serializable by using the [Serializable] attribute before the class declaration.



  • Also, to store a object in ViewState, asp.net must be able to convert it into a stream of bytes so that it can be added to the hidden input field in the page. This process is called serialization.


Example:


[Serializable]

public class Student

{

public string firstName;

public string lastName;
public Student(string fName, string lName)

{

firstName = fName;

lastName = lName;

}

}
//Assigning the value into ViewState
Student std = new Student("Quazi", "Hasan");

ViewState["CurrentStudent"] = std;
//Retrieving the value

Student sampleStudent = (Student) ViewState["CurrentStudent"];

No comments:

Post a Comment