aboutsummaryrefslogtreecommitdiff
path: root/src/AddressBook/SampleUsage.cs
diff options
context:
space:
mode:
authorcsharptest <roger@csharptest.net>2011-05-19 22:18:14 -0500
committerrogerk <devnull@localhost>2011-05-19 22:18:14 -0500
commit1ee7a96b365b43f273d3c55cf84ba25f256613ec (patch)
treea8c2806ac2b00ca6701d93010e709f372e3ecc2f /src/AddressBook/SampleUsage.cs
parent232c79562cebfb46510634afb82a2cf723333404 (diff)
downloadprotobuf-1ee7a96b365b43f273d3c55cf84ba25f256613ec.tar.gz
protobuf-1ee7a96b365b43f273d3c55cf84ba25f256613ec.tar.bz2
protobuf-1ee7a96b365b43f273d3c55cf84ba25f256613ec.zip
Added sample code from the Getting Started Wiki
Diffstat (limited to 'src/AddressBook/SampleUsage.cs')
-rw-r--r--src/AddressBook/SampleUsage.cs44
1 files changed, 44 insertions, 0 deletions
diff --git a/src/AddressBook/SampleUsage.cs b/src/AddressBook/SampleUsage.cs
new file mode 100644
index 00000000..ae7b6802
--- /dev/null
+++ b/src/AddressBook/SampleUsage.cs
@@ -0,0 +1,44 @@
+using System;
+using System.IO;
+
+namespace Google.ProtocolBuffers.Examples.AddressBook
+{
+ class SampleUsage
+{
+ static void Main()
+ {
+ byte[] bytes;
+ //Create a builder to start building a message
+ Person.Builder newContact = Person.CreateBuilder();
+ //Set the primitive properties
+ newContact.SetId(1)
+ .SetName("Foo")
+ .SetEmail("foo@bar");
+ //Now add an item to a list (repeating) field
+ newContact.AddPhone(
+ //Create the child message inline
+ Person.Types.PhoneNumber.CreateBuilder().SetNumber("555-1212").Build()
+ );
+ //Now build the final message:
+ Person person = newContact.Build();
+ //The builder is no longer valid (at least not now, scheduled for 2.4):
+ newContact = null;
+ using(MemoryStream stream = new MemoryStream())
+ {
+ //Save the person to a stream
+ person.WriteTo(stream);
+ bytes = stream.ToArray();
+ }
+ //Create another builder, merge the byte[], and build the message:
+ Person copy = Person.CreateBuilder().MergeFrom(bytes).Build();
+
+ //A more streamlined approach might look like this:
+ bytes = AddressBook.CreateBuilder().AddPerson(copy).Build().ToByteArray();
+ //And read the address book back again
+ AddressBook restored = AddressBook.CreateBuilder().MergeFrom(bytes).Build();
+ //The message performs a deep-comparison on equality:
+ if(restored.PersonCount != 1 || !person.Equals(restored.PersonList[0]))
+ throw new ApplicationException("There is a bad person in here!");
+ }
+}
+}