aboutsummaryrefslogtreecommitdiffhomepage
path: root/csharp/src/AddressBook/SampleUsage.cs
blob: b9a614978c8704740322c75bf2a19a5a4a494e83 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
using System;
using System.IO;

namespace Google.Protobuf.Examples.AddressBook
{
    internal class SampleUsage
    {
        private static void Main()
        {
            byte[] bytes;
            // Create a new person
            Person person = new Person
            {
                Id = 1,
                Name = "Foo",
                Email = "foo@bar",
                Phone = { new Person.Types.PhoneNumber { Number = "555-1212" } }
            };
            using (MemoryStream stream = new MemoryStream())
            {
                // Save the person to a stream
                person.WriteTo(stream);
                bytes = stream.ToArray();
            }
            Person copy = Person.Parser.ParseFrom(bytes);

            // A more streamlined approach might look like this:
            bytes = copy.ToByteArray();
            // And read the address book back again
            AddressBook restored = AddressBook.Parser.ParseFrom(bytes);
            // The message performs a deep-comparison on equality:
            if (restored.Person.Count != 1 || !person.Equals(restored.Person[0]))
            {
                throw new ApplicationException("There is a bad person in here!");
            }
        }
    }
}