I've created a simple class that is a descendant of DynamicObject:
public class DynamicCsv : DynamicObject
{
private Dictionary<string, int> _fieldIndex;
private string[] _RowValues;
internal DynamicCsv(string[] values, Dictionary<string, int> fieldIndex)
{
_RowValues = values;
_fieldIndex = fieldIndex;
}
internal DynamicCsv(string currentRow, Dictionary<string, int> fieldIndex)
{
_RowValues = currentRow.Split(',');
_fieldIndex = fieldIndex;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
result = null;
dynamic fieldName = binder.Name.ToUpperInvariant();
if (_fieldIndex.ContainsKey(fieldName))
{
result = _RowValues[_fieldIndex[fieldName]];
return true;
}
return false;
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
dynamic fieldName = binder.Name.ToUpperInvariant();
if (_fieldIndex.ContainsKey(fieldName))
{
_RowValues[_fieldIndex[fieldName]] = value.ToString();
return true;
}
return false;
}
}
I use the descendant object by doing the following:
protected string[] _currentLine;
protected Dictionary<string, int> _fieldNames;
...
_fieldNames = new Dictionary<string, int>();
...
_CurrentRow = new DynamicCsv(_currentLine, _fieldNames);
When I try to use the _CurrentRow with dot notation:
int x = _CurrentRow.PersonId;
I get the following error message:
"'object' does not contain a definition for 'property' and no extension method 'property' accepting a first argument of type 'object' could be found"
I can resolve the property in the immediate window using VB without any issues though:
? _CurrentRow.PersonId
it looks like _CurrentRow
is typed to object
but that you want dynamic lookup to occur on it. If that's the case then you need to change the type to dynamic
dynamic _CurrentRow;