Translate

> > C# Read Dynamic Class Property (Generic)

C# Read Dynamic Class Property (Generic)

Posted on Tuesday, March 27, 2012 | No Comments

This method can read any class and read all property if a property has string type then perform some operation like remove single quote which create problem to save data in SQL.

public static string RemoveSingleQuote(string data)
        {
            return string.IsNullOrEmpty(data) ? string.Empty : data.Replace("'", "''");
        }

        public static T RemoveSingleQuote<T>(object ob)
        {
            PropertyDescriptorCollection props =
                TypeDescriptor.GetProperties(typeof(T));

            T Tob = (T)ob;
            if (Tob != null)
            {
                for (int i = 0; i < props.Count; i++)
                {
                    PropertyDescriptor prop = props[i];
                    if (prop.PropertyType.Name == "String")
                    {
                        object oPropertyValue = prop.GetValue(Tob);
                        oPropertyValue = RemoveSingleQuote((string)oPropertyValue) as object;
                        prop.SetValue(Tob, oPropertyValue);
                    }
                    //oPropertyValue
                    //table.Columns.Add(prop.Name, prop.PropertyType);
                }
            }
            return Tob;
        }

Leave a Reply

Powered by Blogger.