M.G.
M.G.

Reputation: 133

How can I dynamically initialize items from the class constructor?

In my class constructor I am initializing many List[DropDownItem] lists ..... I don't want to have to list all of them in the constructor anymore, I want them to be initialized auto-magically.

I have the following, which can identify the type I need to target, but I can't get it across the goal line yet. Can't figure out how to do the "obj = new List(); part.

private void initializeDropdownItemLists(Type T)
{
    var props = typeof(UserEditModel).GetProperties();

    foreach (var p in props)
    {
        var type = p.PropertyType;
        if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>))
        {
            var itemType = type.GetGenericArguments()[0];

            if (itemType == typeof(DropdownItem))
            {
                p.SetValue(T, new List<DropdownItem>());
            }
        }

    }
}


public class UserEditModel
{
    public UserEditModel()
    {
        selectedUser = new UserBusinessModel();
        currentUser = new UserBusinessModel();

        //  I want to replace this
        ddl1 = new List<DropdownItem>();
        ddl2 = new List<DropdownItem>();
        ddl3 = new List<DropdownItem>();
        ddl4 = new List<DropdownItem>();
        ddl5 = new List<DropdownItem>();
        ddl6 = new List<DropdownItem>();
        ddl7 = new List<DropdownItem>();
        ddl8 = new List<DropdownItem>();
        ddl9 = new List<DropdownItem>();
        ddl10 = new List<DropdownItem>();

        //  with this
        this.initializeDropdownItemLists();

        //  or better yet this, ..... pass the class type so then any similar class can use it
        someHelper.initializeDropdownItemLists(typeof(UserEditModel));
    }

    public UserBusinessModel currentUser { get; set; }
    public UserBusinessModel selectedUser { get; set; }

    //  other properties omitted for brevity ...
}

Upvotes: 1

Views: 157

Answers (1)

Marcin Iwanowski
Marcin Iwanowski

Reputation: 791

Use the following code:

p.SetValue(someUserEditModelObject, new List<DropdownItem>());

where someUserEditModelObject is object passed to initializeDropdownItemLists method.

EDIT: Code for generic helper:

    public class Helper
    {
        public void InitializeDropdownItemLists<T>(T model)
        {
            var props = typeof (T).GetProperties();

            foreach (var p in props)
            {
                var type = p.PropertyType;
                if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof (List<>))
                {
                    var itemType = type.GetGenericArguments()[0];

                    if (itemType == typeof (DropdownItem))
                    {
                        p.SetValue(model, new List<DropdownItem>());
                    }
                }

            }
        }
    }

Upvotes: 1

Related Questions