tags:

views:

44

answers:

3

Let's say I have this:

dynamic foo = new Foobar();

And I have this:

public class Foobar : DynamicObject
{

}

The question is, is it possible to override members of DynamicObject so that this code:

string name = new Foobar().Name

Does not throw an Exception at run-time? I want to return default for name's if Name is not a member.

Possible? What do I need to override?

+1  A: 

You need to override TryGetMember. Just set to always return true, and provide the default if the member does not exist.

Reed Copsey
How does Foobar know the default though?
SnickersAreMyFave
@CantEatPeanutsDoh: What do you want it to do? You can make it return anything you want. If you want the default to be "Fred", just set the value to "Fred" and you're done...
Reed Copsey
Hm... This comment contradict to your phrase: "I want to return default for name's if Name is not a member". If Foobar doesn't know default, than who knows? You may return null from Foobar.Name property and lets caller decides what default name is.
Sergey Teplyakov
+1  A: 

Override TryGetMember (and TrySetMember). Classes derived from the DynamicObject class can override this method to specify dynamic behavior for operations such as getting a value for a property.

http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.aspx http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.trygetmember.aspx

Ray Henry
A: 

Something like this:

class Foobar : DynamicObject 
{
    private object m_object;

    public ExposedObjectSimple(object obj)
    {
        m_object = obj;
    }

    public override bool TryInvokeMember(
            InvokeMemberBinder binder, object[] args, out object result)
    {
        //Trying to find appropriate property
        var property = m_object.GetType().GetProperty("Name", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
        if (property != null)
        {
            result = (string)property.GetValue(b, null);
            return true;
        }

        result = SomeDefaultName;
        return true;
    }
}
Sergey Teplyakov