Answered by:
Can i get a list of all properties but only in the direvide class?

Question
-
User1034446946 posted
Hi
I have
public class MyClassA { public string ThisProperty {get;set;} public IList<string> GetAllPropertiesFromDerivedClass() { //needs to return One,Two and Three //This will be different if the derived cass is different } } public class MyClassB : MyClassA { public string One {get;set;} public string Two {get;set;} public string Three {get;set;} }
I know i could create an abstract method or virtual method and override it to hard code it (which is what i am doing at the moment), but can i do it dynamically
Any thoughts would be appriciated
Saturday, March 28, 2020 4:49 PM
Answers
-
User711641945 posted
Hi EnenDaveyBoy,
Try this:
public IEnumerable<string> GetAllPropertiesFromDerivedClass() { //needs to return One,Two and Three //This will be different if the derived cass is different var propNames = GetType().GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance) .Select(t=>t.Name); return propNames; }
Result:
Best Regards,
Rena
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Monday, March 30, 2020 6:21 AM
All replies
-
User-474980206 posted
public IList<string> GetAllPropertiesFromDerivedClass() { return this.GetType().GetProperties().Select(p => p.Name).ToList(); }
Saturday, March 28, 2020 6:53 PM -
User753101303 posted
Hi,
With Linq I end up for now with :
public IEnumerable<string> GetAllPropertiesFromDerivedClass() { return GetType().GetProperties().Where(o => o.DeclaringType ==GetType()).Select(o => o.Name); }
ie all propertoes declated in the object type and tkaing names only. Sometimes you may want give a brief overview in case it would be a way to achieve something for which you may have an easier option. What will you do with those property names? Also you have othe rmechanism to get that and mode (such as what does most if not all "data binding" features)
Saturday, March 28, 2020 6:57 PM -
User1034446946 posted
sorry badly worded quetion, I only want to get the ones which are in the Dirived Class File not all in the direived class, so if its an inherited property i want to exclude it.
(I am using reflection to get the value and process it,i have it working but don't like how i have implement it.
Saturday, March 28, 2020 11:01 PM -
User711641945 posted
Hi EnenDaveyBoy,
Try this:
public IEnumerable<string> GetAllPropertiesFromDerivedClass() { //needs to return One,Two and Three //This will be different if the derived cass is different var propNames = GetType().GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance) .Select(t=>t.Name); return propNames; }
Result:
Best Regards,
Rena
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Monday, March 30, 2020 6:21 AM -
User1034446946 posted
works great many thanks
Tuesday, March 31, 2020 11:14 AM