Link to home
Start Free TrialLog in
Avatar of quentinA
quentinAFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Help with c# reflection?

I am trying to write a WPF custom control, and am trying to refactor it so that any List<T> can be converted into a List<CustomType>.

The CustomType has an Id property that I want to be assigned with the value of the Id property from an instance of the source T.

But my problem is how to map the name of the Id property on the source to the Id property on the CustomType.

A pseudocode method follows:

private void UsePropertiesOfInputCollectionInCollectionOfAnotherClass(IEnumerable<object> inputCollection , string nameOfTheMemberThatHoldsTheIdValueOfAnInputObject, Type typeOfTheObjectsInTheCollection)
        {
            foreach (var inputObject in inputCollection)
            {

                //cast the input object to the typeOfTheObjectsInTheCollection


                //interogate the member on the (cast)inputObject that is named: nameOfTheMemberThatHoldsTheIdValueOfAnInputObject


                //Create a new instance of the AnotherClass


                //assign the value of the interogated member to a property called AnotherClass.ClassID



            }
        }


Can you help?
ASKER CERTIFIED SOLUTION
Avatar of Craig Wagner
Craig Wagner
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of quentinA

ASKER

Thanks very much.
It isn't a school assignment (although I often feel as though I am at school, because i'm teaching myself).

I had done following (which works), I'll try yours too.
           var starterObjectType = starterCollection.First().GetType();

            foreach (var starterObject in starterCollection)
            {
                //cast the input object to the typeOfTheObjectsInTheCollection
                MethodInfo castMethod = this.GetType().GetMethod("Cast").MakeGenericMethod(starterObjectType);
                object castedObject = castMethod.Invoke(null, new object[] { starterObject });

                //interogate the member on the (cast)inputObject that is named: nameOfTheMemberThatHoldsTheIdValueOfAnInputObject
                var idResult = GetPropValue(castedObject, nameOfTheMemberThatHoldsTheIdValueOfAnInputObject).ToString();
                var iiid = Guid.Parse(idResult);

                //assign the value of the interogated member to a property called AnotherClass.ClassID
                RecordStarterProperties.Add(new StarterProperty(iiid, textOfTheMember, starterObject));
            }