Alex Hope O'Connor
Alex Hope O'Connor

Reputation: 9704

Creating a class like ASP.NET MVC 3 ViewBag?

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?

Upvotes: 17

Views: 7571

Answers (5)

SepehrM
SepehrM

Reputation: 1097

ViewBag is declared like this:

dynamic ViewBag = new System.Dynamic.ExpandoObject();

Upvotes: 5

Carlos R Balebona
Carlos R Balebona

Reputation: 1926

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

Upvotes: 24

jbtule
jbtule

Reputation: 31799

Behavior wise the ViewBag acts pretty much like ExpandoObject so that maybe what you want to use. However if you want to do custom behaviors you can subclass DynamicObject. The dynamic keyword is important when using these kinds of objects in that it tells to compiler to bind the method calls at runtime rather than compile time, however the dynamic keyword on a plain old clr type will just avoid type checking and won't give your object dynamic implementation type features that is what ExpandoObject or DynamicObject are for.

Upvotes: 8

Richard Schneider
Richard Schneider

Reputation: 35477

I think you want an anonymous type. See http://msdn.microsoft.com/en-us/library/bb397696.aspx

For example:

var me = new { Name = "Richard", Occupation = "White hacker" };

Then you can just get properties as in normal C#

Console.WriteLine(me.Name + " is a " + me.Occupation);

Upvotes: 4

Jacob
Jacob

Reputation: 78890

Use an object of type dynamic. See this article for more information.

Upvotes: 7

Related Questions