Why "is a" Undefined

barski

Junior Contributor
Joined
Apr 7, 2002
Messages
240
Location
Tennessee
Let's say i have a class that is derived from PropertyDescriptor

Code:
public class MyProp : PropertyDescriptor
{
    //implement all abstract methods      
}

why would something like the following return an undefined value or need to be cast
in the first place since MyProp "is a" PropertyDescriptor and PropertyDescriptorCollections contains a collection of PropertyDescriptors
Code:
public class SomeClass
{
        private int id=0;
        private string customer="";
        
        public SomeClass()
        {
              foreach(PropertyDescriptor p in TypeDescriptor.GetProperties(this.GetType()))
              {
                       //MyProp mP = p;//this won't compile type conversion
                         MyProp mP = p;//mp is undefined
                         PropertyDescriptor prD = p//this works
                       
              }
        }

        public int ID{get{return id;}set{id=value;}}
        public string Customer{get{return customer;}set{customer=value;}}

}

if MyProp is a PropertyDescriptor how can this be happening. Any help would be greatly appreciated.
 
The "is a" only works one way round, i.e. MyProp is a PropertyDescriptor but there no guarentee than a PropertyDescriptor is a MyProp.

In other words you can always safetly assign a MyProp object to a variable of type PropertyDescriptor because that is always going to be a safe assignment, there is no way the compiler can verify that the reverse conversion will be true - hence the cast is required.

try using
C#:
foreach(PropertyDescriptor p in TypeDescriptor.GetProperties(this.GetType()))
{
MyProp mP =(MyProp)  p;
}
 
The TypeDescriptor.GetProperties function probably returns multiple PropertyDescriptors - not all of them are of type MyProp though.

You will need to check the type of each p before casting to a MyProp variable.
 
thanks for the reply. figured it out. the answer was in your first reply i just needed to think on it a little more.
 
Back
Top