0

I am struggling to understand how a reflection works in C#. I set a property of class name. When I use a method (below) to validate, i need to get a list of ProductName values. How to do this?

public class Product
{
    public string ProductName
    {
        get;
        set;
    }
}

public class ClassName
 {
    public List<Product> Products
    {
        get;
        set;
    }
 }

App:

product.Add(new Product { ProductName = "whatever name 1" });
product.Add(new Product { ProductName = "whatever name 2" });

Method:

public bool Validate(object obj)
{
        PropertyInfo property = typeof(ClassName).GetProperty("Products");

        Value = (string)property.GetValue(obj, null); // how to get a list of values 
}
3
  • 1
    What is GenericTransaction? Commented Nov 26, 2013 at 10:37
  • Have you tried casting it to list?(List<Product>)property.GetValue(obj, null); Commented Nov 26, 2013 at 10:37
  • Although, it is able to decipher your question... Alex is right, you should at least take the time to read your own question and make sure all the keywords are correct (i.e product/Products as well as Product/GenericTransaction) Commented Nov 26, 2013 at 10:41

1 Answer 1

1

You have to cast it to List<Product>:

public bool Validate(object obj) {
  if(!(obj is ClassName)) return false;
  PropertyInfo property = typeof(ClassName).GetProperty("Products");  
  Value = (List<Product>)property.GetValue(obj, null);
  return true;//or your own validation implemented here
}
Sign up to request clarification or add additional context in comments.

3 Comments

i have tried this but i get error message : Object does not match target type.What is a Value data type?
@user2857908 are you sure obj is of type ClassName, that's your fault.
@user2857908 I updated the Validate method as how it should be, now you should see there is not any exception but the Validate returns false, because the obj passed in is not of type ClassName.

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.