Creating a class like ASP.NET MVC 3 ViewBag?

Alex Hope O'Connor picture Alex Hope O'Connor · Apr 27, 2011 · Viewed 7.2k times · Source

I have a situation where I would like to do something simular to what was done with the ASP.NET MVC 3 ViewBag object where properties are created at runtime? Or is it at compile time?

Anyway I was wondering how to go about creating an object with this behaviour?

Answer

Carlos R Balebona picture Carlos R Balebona · Feb 10, 2013

I created something like this:

public class MyBag : DynamicObject
{
    private readonly Dictionary<string, dynamic> _properties = new Dictionary<string, dynamic>( StringComparer.InvariantCultureIgnoreCase );

    public override bool TryGetMember( GetMemberBinder binder, out dynamic result )
    {
        result = this._properties.ContainsKey( binder.Name ) ? this._properties[ binder.Name ] : null;

        return true;
    }

    public override bool TrySetMember( SetMemberBinder binder, dynamic value )
    {
        if( value == null )
        {
            if( _properties.ContainsKey( binder.Name ) )
                _properties.Remove( binder.Name );
        }
        else
            _properties[ binder.Name ] = value;

        return true;
    }
}

then you can use it like this:

dynamic bag = new MyBag();

bag.Apples = 4;
bag.ApplesBrand = "some brand";

MessageBox.Show( string.Format( "Apples: {0}, Brand: {1}, Non-Existing-Key: {2}", bag.Apples, bag.ApplesBrand, bag.JAJA ) );

note that entry for "JAJA" was never created ... and still doesn't throw an exception, just returns null

hope this helps somebody