barski Posted February 28, 2008 Posted February 28, 2008 Let's say i have a class that is derived from PropertyDescriptor 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 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. Quote
Administrators PlausiblyDamp Posted February 28, 2008 Administrators Posted February 28, 2008 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 foreach(PropertyDescriptor p in TypeDescriptor.GetProperties(this.GetType())) { MyProp mP =(MyProp) p; } Quote Posting Guidelines FAQ Post Formatting Intellectuals solve problems; geniuses prevent them. -- Albert Einstein
barski Posted February 28, 2008 Author Posted February 28, 2008 thanks for the reply. Error Specified Cast invalid Quote
Administrators PlausiblyDamp Posted February 28, 2008 Administrators Posted February 28, 2008 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. Quote Posting Guidelines FAQ Post Formatting Intellectuals solve problems; geniuses prevent them. -- Albert Einstein
barski Posted February 28, 2008 Author Posted February 28, 2008 thanks for the reply. figured it out. the answer was in your first reply i just needed to think on it a little more. Quote
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.