Skip to content

Instantly share code, notes, and snippets.

@codeimpossible
Created September 18, 2012 05:12
Show Gist options
  • Save codeimpossible/3741390 to your computer and use it in GitHub Desktop.
Save codeimpossible/3741390 to your computer and use it in GitHub Desktop.
The simplest example of DynamicObject I could come up with...
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace AWordAboutDynamic
{
class Program
{
public class PersonData : DynamicObject
{
private Dictionary<string, object> _store = new Dictionary<string, object>();
public override bool TryGetMember( GetMemberBinder binder, out object result )
{
if( _store.ContainsKey( binder.Name ) )
{
result = _store[ binder.Name ];
return true;
}
return base.TryGetMember( binder, out result );
}
public override bool TrySetMember( SetMemberBinder binder, object value )
{
if( _store.ContainsKey( binder.Name ) )
{
_store[ binder.Name ] = value;
}
else
{
_store.Add( binder.Name, value );
}
return true;
}
public string ToJson()
{
var builder = new StringBuilder();
using( var writer = new StringWriter( builder ) )
new JsonSerializer().Serialize( writer, _store );
return builder.ToString();
}
}
static void Main( string[] args )
{
// create a new persondata
dynamic personData = new PersonData(); // show how this won't work if you use "var"
// set a value into our persondata
personData.name = "Jared Barboza";
personData.address = new
{
address1 = "10 main st",
address2 = "apt 12",
city = "Boston",
state = "Massachusetts",
zipcode = "01754"
};
Console.WriteLine( personData.ToJson() );
Console.ReadLine();
}
}
}
@codeimpossible
Copy link
Author

oops, forgot to say that this requires Json.net...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment