1

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?

1 Answer 1

4

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Wow, I don't know whether to feel dumb because I missed that or to feel overjoyed because a celebrity answered my question :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.