Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How To Access Class Properties From A Base Abstract Class

I’m trying to design a base abstract class that can gather all the properties from classes that are inherited from it. I’m getting the name fine, but getting the value is not working. I get the runtime error "Object does not match target". Any help is much appreciated.

 public string Get()
    {
        string ret = "";
        var type = GetType();
        foreach (PropertyInfo p in this.GetType().GetProperties())
        {
             ret += p.Name + "`" + p.GetValue(type) + "~";
            //i've also tried
            //ret += p.Name + "`" + p.GetValue(this) + "~";
        }

        ret = ret.TrimEnd('~');
        return ret;
    }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Parameter count mismatch.

It seems that one of the properties is an indexer, you can ignore such properties by checking GetIndexParameters on the PropertyInfo (or process it accordingly if needed):

if (!p.GetIndexParameters().Any())
{
    ret += p.Name + "`" + p.GetValue(this) + "~";
}

Demo with the runtime exception @sharplab.io.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading