By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
448,570 Members | 1,339 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 448,570 IT Pros & Developers. It's quick & easy.

Base Class Prop not hidden to Reflection

P: n/a
Hello,

I'm encountering an unexpected behavior when using
the "new" modifier in a derived class to hide an inherited
base class property. I use "new" intentionally so I can
change the Type of the property in the derived class, and
I can use the derived class as expected through standard
instantiation. The unexpected behavior occurs when I try
to set gather the PropertyInfo for the derived class
property via Reflection. I get an AmbiguousMatchException
as both the base class and derived class property
implementations are found. Perhaps I don't fully
understand the "new" modifier - I expected the base class
member to be hidden completely when working with the
derived class. I have included a code sample that
illustrates the behavior. If anyone could explain this, I
would be very interested in understanding. Thanks.

using System;
using System.Reflection;

namespace TestHide
{
class foo
{

[STAThread]
static void Main(string[] args)
{
Derived d = new Derived( "test" );

Console.WriteLine( "PropType:\t" +
d.Problem.GetType().ToString() );

try
{
PropertyInfo p = d.GetType().GetProperty
( "Problem" );
}
catch(AmbiguousMatchException e)
{
Console.WriteLine( "Error:\t\t" + e.Message );

PropertyInfo[] p = d.GetType().GetProperties();
for( int n = 0; n < p.Length; n++ )
{
Console.WriteLine( "Name: " + p[n].Name
+ "\tType: " + p[n].PropertyType
+ "\tDecl: " + p[n].DeclaringType );
}
}
catch(Exception e)
{
Console.WriteLine( e.Message );
}
}

}
public class Base
{
protected int _works = 0;
protected object _problem = null;

public Base(){}

public virtual int Works
{
get
{
return _works;
}
set
{
_works = value;
}
}

public virtual object Problem
{
get
{
return _problem;
}
set
{
_problem = value;
}
}
}

public class Derived : Base
{

public Derived(){}

public Derived(string problem)
{
this.Problem = problem;
}

public override int Works
{
get
{
return base.Works - 1;
}
set
{
base.Works = value + 2;
}
}

public new string Problem
{
get
{
return (string)base.Problem;
}
set
{
base.Problem = (string)value;
}
}
}
}

Jul 21 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
Sorry, forgot the output from the code listing.

PropType: System.String
Error: Ambiguous match found.
Name:Works Type:System.Int32 Decl:TestHide.Derived
Name:Problem Type:System.String Decl:TestHide.Derived
Name:Problem Type:System.Object Decl:TestHide.Base
Jul 21 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.