Devlico.Us
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @devlicious

Christopher Bennage

Our WPF book is now available!


Reflecting Virtual Properties

I experienced an interesting gotcha with reflection today. I had a base class with a virtual property:

class BaseClass
    {
        private string _someProperty = "Hello!";

        public virtual string SomeProperty
        {
            get { return _someProperty; }
            set { _someProperty = value; }
        }
    }

In a subclass I overrode the property, but only implemented the setter:

class SubClass : BaseClass
    {
        public override string SomeProperty
        {
            set { base.SomeProperty = value + " and stuff"; }
        }
    }
 

You can get/set the property of an instance of SubClass normally.  However, if you try to get the property's value with reflection, it's not quite straightforward.  Something like this, won't work:

    SubClass sub = new SubClass();
    Type t = sub.GetType();
    PropertyInfo prop = t.GetProperty("SomeProperty");
    string s = prop.GetValue(sub, null).ToString();

The call to GetValue() fails because the getter doesn't exist on the SubClass.  It sounds obvious in retrospect, but it sure threw me for a loop today.  See the attachment for a working example.



Comments

Bob said:

yeah i bet

# October 26, 2006 10:09 AM

About Christopher Bennage

Christopher is a software developer and consultant at Blue Spire Consulting, a company he co-founded with Rob Eisenberg in 2006. He is a Christian, a marginal musician, and an armchair philosopher. His interests include programming, liberal education, science, truth, beauty, and a number of deceased British authors (C. S. Lewis, G. K. Chesterton, and most recently Owen Barfield.) He lives in Tallahassee, FL with his wife and three children and still prefers to play as the Night Elves in WarCraft 3. Check out Devlicio.us!

Our Sponsors

Red-Gate!