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 imagehelp@codebetter.com
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:

[Advertisement]

About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Subscribe
Google Reader or Homepage

del.icio.us CodeBetter.com Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl CodeBetter.com Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of Devlicio.us
Red-Gate Tools For SQL and .NET

NDepend

SlickEdit
 
SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
LiteAccounting.Com
DevExpress
Fixx
NHibernate Profiler
Unfuddle
Balsamiq Mockups
Scrumy
JetBrains - ReSharper
Umbraco
NServiceBus
RavenDb
Web Sequence Diagrams
Ducksboard<-- NEW Friend!

 



Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers

 

Community Server (Commercial Edition)