0

I have a custom dynamic objects which is internally just a dictionary, but allows to access it's values as if their being compile time properties.

It's (more or less) just this:

public class Dummy : DynamicObject, IEnumerable<KeyValuePair<string, object>>
{
    private readonly Dictionary<string, object> _values...

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        result = _values[binder.Name];
        return true;
    }
    ...

Setting and getting 'properties' works fine, but since my object technically implements IEnumerable<'1>, I'd like to call methods from IEnumerable<'1> on it.

However, whenever I call e.g. Count(), TryGetMember gets invoked which of course doesn't make sense:

The key 'Count()' was not present in the dictionary.

Is there a way to get around this?

xvdiff
  • 2,179
  • 2
  • 24
  • 47
  • I cannot replicate your problem. Can you show how you're calling `Count()`? – D Stanley Feb 06 '15 at 16:32
  • Also, `Count` is not a method on `IEnumerable` - it is an _extension method_ that the compiler translates into a call to the static method `Enumerable.Count`. – D Stanley Feb 06 '15 at 16:33

1 Answers1

0

Simply put you can't use extension methods with dynamic objects using the normal syntax. You can use Enumerable.Count(dummyInstance); though but I doubt this is what you want.

See [Extension method and dynamic object for details.

Community
  • 1
  • 1
Jessica
  • 380
  • 1
  • 7
  • I'm not quite sure if I understand this correctly. I always thought extensions methods are just syntactical sugar that translate to a static method call with the member being called on as the first parameter? So list.Count() becomes Enumerator.Count(list) after compiling, so this shouldn't have anything to do with the instance being dynamic, or object, or whatever? – xvdiff Feb 06 '15 at 17:25
  • Yes, exactly, it's syntactic sugar. Which means it's done at compile time. It seems like the compiler should know that you're instantiating a Dummy class and therefore should treat the dynamic object as an IEnumerable during compilation but it doesn't actually do this and thus it doesn't know which static method to call. Does that make sense? – Jessica Feb 06 '15 at 17:44