IObject is an interface in C# that provides a blueprint for any class to implement custom properties and methods. It is used to make the code more flexible, scalable, and maintainable.
Example 1: Serialization
One of the most common uses of IObject is for serialization, which allows an object to be converted to a byte stream for storage or transmission. The System.Runtime.Serialization package library provides support for this functionality.
using System; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary;
[Serializable] class Person : IObject { public string Name { get; set; } public int Age { get; set; }
public Person(string name, int age) { Name = name; Age = age; } }
static void Main(string[] args) { Person p1 = new Person("Jane", 30);
// Serialize BinaryFormatter formatter = new BinaryFormatter(); MemoryStream memoryStream = new MemoryStream(); formatter.Serialize(memoryStream, p1);
// Deserialize memoryStream.Seek(0, SeekOrigin.Begin); Person p2 = (Person)formatter.Deserialize(memoryStream);
Console.WriteLine(p2.Name + ", " + p2.Age); }
Example 2: JSON Serialization
Another popular use of IObject is for serializing objects into JSON format. The Newtonsoft.Json package library provides support for JSON serialization and deserialization.
using Newtonsoft.Json;
class Person : IObject { public string Name { get; set; } public int Age { get; set; }
public Person(string name, int age) { Name = name; Age = age; } }
static void Main(string[] args) { Person p1 = new Person("Jane", 30);
// Serialize to JSON string json = JsonConvert.SerializeObject(p1);
// Deserialize from JSON Person p2 = JsonConvert.DeserializeObject(json);
Console.WriteLine(p2.Name + ", " + p2.Age); }
In both examples, the IObject interface is used to define the schema of the object, which allows for easy serialization and deserialization using the appropriate package library.
C# (CSharp) IObject - 60 examples found. These are the top rated real world C# (CSharp) examples of IObject extracted from open source projects. You can rate examples to help us improve the quality of examples.