Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at
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.

Posted 09-21-2006 9:17 PM by Christopher Bennage
Filed under:


About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Google Reader or Homepage Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of
Red-Gate Tools For SQL and .NET


SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
NHibernate Profiler
Balsamiq Mockups
JetBrains - ReSharper
Web Sequence Diagrams
Ducksboard<-- NEW Friend!


Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers


Community Server (Commercial Edition)