"Dynamic object does not contain a definition" error in same namespace

This is my first try at dynamic objects. I have a class "Cell" which contains string ID and float value. What I wanted is to take a list of Cells and create one dynamic object with all its IDs and values as properties.

Here is my "DynamicRow":

namespace WPFView
{
    public class DynamicRow : DynamicObject
    {
        public List<Cell> Cells;
        public DynamicRow(List<Cell> cells)
        {
            Cells = new List<Cell>(cells);
        }

        public string GetPropertyValue(string propertyName)
        {
            if (Cells.Where(x => x.ID == propertyName).Count() > 0)
            {
                //Cell.GetValueString() returns the float value as a string
                return Cells.Where(x => x.ID == propertyName).First().GetValueString();
            }
            else
            {
                return string.Empty;
            }
        }

        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            result = GetPropertyValue(binder.Name);
            return string.IsNullOrEmpty(result as string) ? false : true;
        }
    }
}

I tried testing it with this:

namespace WPFView
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            //ArithmeticCell is derived from Cell
            List<Cell> cells = new List<Cell> { new ArithmeticCell { ID = "NA2_DIR", Value = 1234 } };
            DynamicRow dRow = new DynamicRow(cells);

            MessageBox.Show(dRow.NA2_DIR);
        }
    }
}

With this I get a compiler error

'WPFView.DynamicRow' does not contain a definition for 'NA2_DIR' and no extension method 'NA2_DIR' accepting a first argument of type 'WPFView.DynamicRow' could be found

I read some similar questions but their problem was that the dynamic object was defined in a different assembly than the calling method. In my case dynamic object is in the same project and namespace as the calling method.

How do I go about this error?

Jon Skeet
people
quotationmark

The problem is that the compile-time type of your dRow variable is DynamicRow - so the compiler doesn't treat it as a dynamic value.

You need to declare the type as dynamic so that execution-time binding is performed:

dynamic dRow = new DynamicRow(cells);

people

See more on this question at Stackoverflow