Thursday, 21 July 2016

Pass and Return different class in generic class for Reflection

No comments
Generic (Reflection) Method

 public System.Collections.Generic.List<T> GetValues<T>(object t) where T : class
        {          
            System.Collections.Generic.List<T> lstUserAppconfig = new System.Collections.Generic.List<T>();
            foreach (PropertyInfo info in t.GetType().GetProperties())
            {
                if (Enum.IsDefined(typeof(Constant.Menus), info.Name))//check if value is in enum
                {
                    if (!string.IsNullOrEmpty((string)info.GetValue(t, null)))
                    {
                        UserAppconfig userAppconfig = new UserAppconfig();
                        userAppconfig.appconfigid = (int)Enum.Parse(typeof(Constant.Menus), info.Name);
                        userAppconfig.userid = SessionFactory.Instance.CurrentUsers.userid;
                        userAppconfig.value = (string)info.GetValue(t, null);
                        lstUserAppconfig.Add((T)Convert.ChangeType(userAppconfig, typeof(T)));
                    }
                }
            }
            return lstUserAppconfig;

        }

Calling method

UserAppconfigModel userAppconfigModel=new UserAppconfigModel()

System.Collections.Generic.List<UserAppconfig> lstUserAppconfig=GetValues<UserAppconfig>(userAppconfigModel);