0

I have the following array:

"someData.childData.child1","someData.childData.child2", etc.

How do I convert this string array to objects. That is, someData.childData.child1, someData.childData.child2,... are all objects.

6
  • 4
    Have a look into .NET Reflection. Commented Jan 8, 2015 at 9:01
  • What do you mean by "converting to objects" ? do you want to evaluate the value of the specified object ("someData.childData.child1") ? Commented Jan 8, 2015 at 9:03
  • "someData.chidData.child1, someData.chidData.child2" are all objects or types? Using reflection you can work with types. Commented Jan 8, 2015 at 9:03
  • Yes, I want the evalute the value of the specified object. Commented Jan 8, 2015 at 9:07
  • 3
    This sort of seems like an XY problem... what are you actually trying to do? reflection can give slower performance than potential alternatives Commented Jan 8, 2015 at 9:10

1 Answer 1

1

You need to use Reflection as follows

      string[] yourArray = new string[] { "someData.childData.child1", "someData.childData.child2" };
        System.Collections.Generic.List<dynamic> CreatedAll = new System.Collections.Generic.List<dynamic>();
        for (int i = 0; i < yourArray.Length; i++)
        {
            string objStr = yourArray[i];
            string[] objs = objStr.Split('.');
            System.Collections.Generic.List<dynamic> created = new System.Collections.Generic.List<dynamic>();
            for (int j = 0; j < objs.Length; i++)
            {
                var myObj = System.Activator.CreateInstance("namespaceName", objs[j]);
                created.Add(myObj);
            }

            System.Reflection.PropertyInfo propertyInfo = created[1].GetType().GetProperty(objs[2]);
            propertyInfo.SetValue(created[1], created[2], null);


            System.Reflection.PropertyInfo propertyInfo1 = created[0].GetType().GetProperty(objs[1]);
            propertyInfo1.SetValue(created[0], created[1], null);
            CreatedAll.Add(created);
        }
Sign up to request clarification or add additional context in comments.

Comments

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.