0

Just started studying reflection and im having a lot of issues. I want to cast to find the type of properties and then set them. So i wanted to cast to these properties type.

protected override object Load(SqlDataReader dr)
        {
            object item = Activator.CreateInstance(klass);



            foreach (var p in klass.GetProperties())
            {
                MethodInfo pSet = p.GetSetMethod();
                Type pType= p.PropertyType;
                object setParam = dr[p.Name]; 
                object[] paramArray = (object[])Array.CreateInstance(pType, 1);
                paramArray[0] = setParam;
                pSet.Invoke(item, paramArray);
            }
            return item;
        }
2
  • 1
    You really should include the errors that you are getting or what results you get and what you expect to get. Also where does klass come from? Is it a Type variable or just the actual name of the class? Commented Mar 19, 2018 at 15:36
  • 1
    This looks like another attempt at reinventing Dapper, which is fine if you're doing it for educational purposes, but not a hot idea if you want to use it for production code. (For starters, this approach is terribly slow, relatively speaking.) Commented Mar 19, 2018 at 15:39

1 Answer 1

1

As they said you need to add your errors, but from what i see you have two problems:

You use klass as Type instead of typeof(klass) You try to cast a whole array to a new type - this can be solved using Array.ConvertAll... but the easier way would be to just initialize a regular array using: object[] paramArray = new object[1].

good luck

Sign up to request clarification or add additional context in comments.

2 Comments

New to c# and reflection as this is for college. The class has a property of the type Type named klass
So again, please add more code and errors. Anyway, did you try changing the casting as i suggested?

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.