I want to loop through my Car class with reflection to remove all null values and replace them with better values like string = “”.
[Serializable()]
public class Car
{
public string model;
public int year;
public List<Owner> owner;
}
[Serializable()]
public class Owner
{
public string firstName;
public string lastName;
}
I have made this so far
public void LoopEverythingAndFix(object type)
{
var prop = type.GetType().GetFields();
foreach (var fieldInfo in prop)
{
if (GetType(fieldInfo))
{
var value = fieldInfo.GetValue(type);
if (value == null)
fieldInfo.SetValue(type, GetDefaultValue(fieldInfo));
}
else
{
LoopEverythingAndFix(fieldInfo);
}
}
}
public bool GetType(System.Reflection.FieldInfo fieldInfo)
{
if (fieldInfo.FieldType == typeof(string))
return true;
if (fieldInfo.FieldType == typeof(bool))
return true;
if (fieldInfo.FieldType == typeof(int))
return true;
if (fieldInfo.FieldType == typeof(decimal))
return true;
return false;
}
The GetType method is to know if current field is a class like “owner” class or if its a value/reference field like int/string,and if it is a type of “owner” then i want to loop that to and fix those properties as well.
The problem is when it finds “owner” in car class, and goes to execute :
LoopEverythingAndFix(fieldInfo);
thats where the problem is, because i send fieldInfo to the method LoopEverythingAndFix and when it goes back in the loop it gets 0 fields at type.GetType().GetFields(). It is a list and i want to loop the listitems and send them to the LoopEverythingAndFix method
You’re trying to call
LoopEverythingAndFixon the Reflection typeFieldInforather than the actual object you want to fix.To fix, replace this:
With this: