views:

25

answers:

1

I have written this class-methods for .net 2.0 to create objects from '|'-separated strings and vise-versa.

But the problem is, they are not giving right results in case of Inherted types, i.e. inherited properties are coming last and the sequence of the data supplied in the form of a '|'-separated string is not working.

For example:

class A
{
    int ID;
}

class B : A
{
    string Name;
}

the string is "1|John". the methods are reading as the name==1 and ID=="John".

Please tell me how to do it.

public class ObjectConverter<T>
    {
        public static T TextToObject(string text)
        {
            T obj = Activator.CreateInstance<T>();
            string[] data = text.Split('|');
            PropertyInfo[] props = typeof(T).GetProperties();
            int objectPropertiesLength = props.Length;            

            int i = 0;

            if (data.Length == objectPropertiesLength)
            {
                for (i = 0; i < objectPropertiesLength; i++)
                {
                    props[i].SetValue(obj, data[i], null);
                }
            }

            return obj;
        }

        public static string ObjectToText(T obj)
        {
            StringBuilder sb = new StringBuilder();

            Type t = typeof(T);

            PropertyInfo[] props = t.GetProperties();

            int i = 0;
            foreach (PropertyInfo pi in props)
            {
                object obj2 = props[i++].GetValue(obj, null);

                sb.Append(obj2.ToString() + "|");
            }

            sb = sb.Remove(sb.Length - 1, 1);

            return sb.ToString();
        }
    }
+1  A: 
  • I don't think the runtime assures you that when you call getproperties the property info objects will always be in the same order. You will need to do something like get the list of property names sort them and use the same sorting for serialization and deserialization .

  • There are at least 3 ways to serialize object built into .net is there a reason why you are not using one of those

rerun