1

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.

2
  • You've gone to the bother of requesting from the generics system that any type you're supplied has a parameterless constructor - so why not just new TEntity() rather than Activator.CreateInstance(...)? Commented Jul 29, 2016 at 10:49
  • I had some thought process and was just doodling around with the code. I was using new TEntity() before. Commented Jul 29, 2016 at 10:52

1 Answer 1

5

In your SetValue you still have to give the instance of the owner of the property: someBusinessEntity.

object instance = new TEntity();

// And then
propertyInfo.SetValue(someBusinessEntity, instance);

Note that your logic seems odd to me. You are using a generic type to set all properties. Why not use the type of the property?

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Patrick. It works. Im quite new to reflection and don't quite understand your last part.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.