vendredi 29 juillet 2016

C# Reflection, setting new instance of a null property

I've writing a small method whose sole purpose is to check if a property is null for a given class. If the property is null, then create a new instance of it. I'm getting stuck on part where I'm actually setting a value:

  public static void CheckIfPropertyIsNull<TEntity>(SomeBusinessEntity someBusinessEntity) where TEntity : new()
    {
        var properties = typeof(SomeBusinessEntity).GetProperties();

        foreach (PropertyInfo propertyInfo in properties)
        {
            Type currentType = propertyInfo.PropertyType;
            if (currentType == typeof(TEntity))
            {
                var propertyData = propertyInfo.GetValue(someBusinessEntity, null);
                if (propertyData == null)

                {
                    object instance = Activator.CreateInstance(typeof(TEntity));

                    // And then?
                    //propertyInfo.SetValue(null, instance);

                    return;
                }
            }
        }
    }

I try to use the SetValue() method but with no luck.





Aucun commentaire:

Enregistrer un commentaire