Adding a property to an existing class

I have a private class that I use to implement certain properties. Thus, I have no way to modify the actual private class and do not want to use inheritance to create my own class instead. Is there a way to add properties to this private class?

Thanks!

+4
source share
2 answers

If you can access the data in the appropriate class and can use methods instead of properties, check out the extension methods introduced in C # 3.0. From this article, an extension method is added here, added to the (private, non-mutable) String class:

public static class MyExtensions { public static int WordCount(this String str) { return str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length; } } 

From horse mouth , expansion properties are possible in a future version of C #.

This will not help you if you need to access private fields or methods. In this case, you can think about it, but I would advise you to stay away from this, if it is really necessary - sometimes it can be messy.

+9
source

If the purpose of the properties is data binding, then you can add runtime properties to types outside of your control using TypeDescriptionProvider , which is the factory for ICustomTypeDescriptor . Then you bind the original provider and create a custom PropertyDescriptor that receives additional data.

It's easy enough for additional read-only properties that are calculated based on existing properties (and “reasonably easy”, I mean “just a little crazy”), but for read and write properties (or properties that are independent of existing participants), this is very difficult, since you need to figure out where to put these values (in such a way as to still collect garbage, etc.). Nontrivial.

+1
source

All Articles