I want to make my code look cleaner and 'express its intent' more..
The following method is reflecting over two types and checking that if there is a property in one type, then there is a corresponding property of the same name in the other type. If there is then it sets the value of the property to the index variable. otherwise it throws an exception which is caught and logged from the calling code.
Watching videos and looking through other code bases its sometimes easy to see at a glance what the code is doing but im not happy with this method as I feel at first glance it just looks like a mess and to understand it you really have to read it through rather than glance at it. Does anyone have any tips to improve readability etc?
private void GenerateFieldIndexes()
{
Type thisType = GetType();
Type tnsType = typeof (T);
Dictionary<string, PropertyInfo> indexInfos = new Dictionary<string, PropertyInfo>();
string formattedName;
// We need to start from 2 as first two fields are always hard coded
int index = 2;
foreach (PropertyInfo property in tnsType.GetProperties())
{
formattedName = property.Name.Trim().ToLower();
indexInfos[formattedName] = property;
}
PropertyInfo p;
foreach (PropertyInfo property in thisType.GetProperties())
{
formattedName = property.Name.Trim().ToLower();
if (!indexInfos.ContainsKey(formattedName))
throw new FieldNameMissingException(string.Format("{0} Property name {1} missing!", GetType(),
formattedName));
p = GetProperty(thisType, formattedName);
if (p == null)
throw new FieldNameMissingException(string.Format("{0} Property name {1} missing!", GetType(),
formattedName));
p.SetValue(thisType, index, null);
FieldNames.Add(formattedName);
index++;
}
}
private PropertyInfo GetProperty(Type t, string propertyName)
{
return t.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase);
}