So I have a method that parses an address field coming in and depending on its length, it needs to write to one or more fields(don't ask...Db2 legacy code needed). Currently we have this method implemented for every class that this is required in and I wanted to write a generic method, which I have to some degree accomplished. The problem is that while how we parse out the address field is the same for each object, the property names used are different depending on which class it is.
This then requires me to check the type of object being passed in and then do a double cast (ClassType)(object) to be able to access the properties and set them properly, then do another double cast (T)(object) to return the generic list.
This is inefficient and basically somewhat defeats the purpose of using generics to begin with. Is there a better way to get the same functionality without having to do type checks and double casts to be able to access the class properties?
public List<T> ParseLongNameStreetName<T>(List<T> myList)
{
myList.ForEach(item =>
{
if (item.GetType() == typeof(DP1)) {
DP1 castItem = (DP1)(object)item;
dynamic streetName = ParsedStreetName(castItem.MA1 + " " + castItem.MA2);
castItem.MA1 = streetName.add1;
castItem.MA2 = streetName.add2;
castItem.MA3 = streetName.add3;
item = (T)(object)castItem;
}
else if (item.GetType() == typeof(DI1))
{
DI1 castItem = (DI1)(object)item;
dynamic streetName = ParsedStreetName(castItem.MA1 + " " + castItem.MA2);
castItem.MA1 = streetName.add1;
castItem.MA2 = streetName.add2;
castItem.MA3 = streetName.add3;
item = (T)(object)castItem;
}
else if (item.GetType() == typeof(DW1))
{
DW1 castItem = (DW1)(object)item;
dynamic streetName = ParsedStreetName(castItem.AD1 + " " + castItem.AD2);
castItem.AD1 = streetName.add1;
castItem.AD2 = streetName.add2;
castItem.AD3 = streetName.add3;
item = (T)(object)castItem;
}
});
return myList;
}
private dynamic ParsedStreetName(string address)
{
string add1 = string.Empty;
string add2 = string.Empty;
string add3 = string.Empty;
int addLen = address.Length;
try
{
add1 = addLen > 30 ? address.Substring(0, 30) : address.Substring(0, addLen);
add2 = addLen > 30 ? addLen > 60 ? address.Substring(29, 30) : address.Substring(30, addLen - 30) : "";
add3 = addLen > 60 ? address.Substring(59, addLen - 60) : "";
} catch(Exception ex)
{
Console.WriteLine(ex);
}
return new { add1, add2, add3 };
}