Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have an object that is contains strings and further objects that contain strings, what i need to do is ensure that the object and any sub objects have an empty string and not a null value, so far this works fine:

foreach (PropertyInfo prop in contact.GetType().GetProperties())
{
    if(prop.GetValue(contact, null) == null)
    {
        prop.SetValue(contact, string.empty);
    }
}

the problem is this only works for the objects strings and not the sub-objects strings. Is there a way to also loop over all sub-objects and set their strings to string.Empty if found to be null?

Here's an example of the 'contact' object:

new contact 
{
  a = "",
  b = "",
  c = ""
  new contact_sub1 
  {
     1 = "",
     2 = "",
     3 = ""
  },
  d = ""
}

Basically I also need to check in contact_sub1 for nulls and replace the value with an empty string.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
228 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can modify your current code to get all sub objects and then perform the same check for null string properties.

public void SetNullPropertiesToEmptyString(object root) {
    var queue = new Queue<object>();
    queue.Enqueue(root);
    while (queue.Count > 0) {
        var current = queue.Dequeue();
        foreach (var property in current.GetType().GetProperties()) {
            var propertyType = property.PropertyType;
            var value = property.GetValue(current, null);
            if (propertyType == typeof(string) && value == null) {
                property.SetValue(current, string.Empty);
            } else if (propertyType.IsClass && value != null && value != current && !queue.Contains(value)) {
                queue.Enqueue(value);
            }
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...