// Create a new instance of a class var person = new Person("John", "Doe", 30); // Serialize the object var formatter = new BinaryFormatter(); var stream = new MemoryStream(); formatter.Serialize(stream, person); // Deserialize the object stream.Seek(0, SeekOrigin.Begin); var deserializedPerson = formatter.Deserialize(stream); // Retrieve the value of a field using GetValueNoThrow var info = new SerializationInfo(person.GetType(), new FormatterConverter()); info.AddValue("age", 40); var age = (int)info.GetValueNoThrow("age", typeof(int)); Console.WriteLine(age); // Output: 40
// Define a class with a property public class Person { public string FirstName { get; set; } public string LastName { get; set; } public int Age { get; set; } public Person(string firstName, string lastName, int age) { FirstName = firstName; LastName = lastName; Age = age; } } // Serialize and deserialize the object var person = new Person("John", "Doe", 30); var formatter = new BinaryFormatter(); var stream = new MemoryStream(); formatter.Serialize(stream, person); stream.Seek(0, SeekOrigin.Begin); var deserializedPerson = formatter.Deserialize(stream); // Retrieve the value of a property using GetValueNoThrow var info = new SerializationInfo(deserializedPerson.GetType(), new FormatterConverter()); info.AddValue("FirstName", "Jane"); var firstName = (string)info.GetValueNoThrow("FirstName", typeof(string)); Console.WriteLine(firstName); // Output: JaneIn this example, we define a `Person` class with three properties: `FirstName`, `LastName`, and `Age`. We then serialize and deserialize the object using a `BinaryFormatter`. After that, we create a new instance of `SerializationInfo` and add a value to it using the `AddValue` method. Finally, we retrieve the value of the "FirstName" property using `GetValueNoThrow` and print it to the console. In conclusion, the System.Runtime.Serialization package in C# provides support for serialization, including the `SerializationInfo` class and its methods like `GetValueNoThrow`. These methods allow us to retrieve the values of fields and properties from serialized objects without raising exceptions.