Question: Dynamic object with string properties


Dynamic object with string properties

Answers 0
Added at 2017-11-07 18:11

I have been working with custom dynamic objects, that access an underlying data row or dictionary, for example:

public class DictionaryX : DynamicObject
        private readonly Dictionary<string, string> _dict;

        public DictionaryX(Dictionary<string, string> dict) { _dict = dict; }

        public override bool TryGetMember(GetMemberBinder binder, out object result)
            var retVal = _dict.ContainsKey(binder.Name);
            result = retVal ? _dict[binder.Name] : null;
            return retVal;

This makes reading and writing the code a lot easier, eg in the case of a DataRow

var fullName = row.Name + row.Surname;

Instead of

var fullName = row.Field("Name") + row("Surname");

But what we really want is for the accessed property to be type string instead of dynamic. The data is always a string in the underlying object, but in places we have to cast as string or declare them as string instead of 'var', otherwise we can get compile or runtime errors eg when passing to other methods

string fullName = row.Name + row.Surname

This undoes some of the work of making it nicer code to work with. I'd like to make an DynamicStringObject that allows me to write code in this way but accessed properties are always strings, but I'm not really sure where to start.

Answers to

Dynamic object with string properties

Source Show
◀ Wstecz