I work with custom dynamic objects that access a basic data string 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 it easier to read and write code, for example, in the case of a DataRow
var fullName = row.Name + row.Surname;
Instead
var fullName = row.Field("Name") + row("Surname");
But we really want the available property to be a type string instead of a dynamic one. The data is always a string in the base object, but in some places we must cast it or declare it as a string instead of "var", otherwise we may get compilation or execution errors, for example, when passing to other methods
string fullName = row.Name + row.Surname DoSomething(fullName); DoSomethingElse((string)row.Surname);
This will cancel some of the work of creating more convenient code for the job. I would like to create a DynamicStringObject that allows me to write code this way, but accessing properties is always a string, but I'm not sure where to start.
source share