Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a Property to an existing class

Tags:

c#

properties

I have a private class that I'm using to implement certain properties. As such, I don't have the ability to modify the actual private class, and don't want to use inheritance to create my own class in place of it. Is there a way where I can add properties to that private class?

Thanks!

like image 357
locoboy Avatar asked Dec 28 '22 07:12

locoboy


2 Answers

If you can access the data in the class that you need, and can live with methods instead of properties, look into extension methods, introduced in C# 3.0. From that article, here's an extension method added to the (sealed, non-modifiable) String class:

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

From the horse's mouth, extension properties are a possibility in a future version of C#.

This won't help you if you need to access private fields or methods. In that case, you might look into reflection, but I'd advise staying away from that unless it's really necessary - it can get messy sometimes.

like image 78
Michael Petrotta Avatar answered Jan 10 '23 12:01

Michael Petrotta


If the purpose of the properties is for data-binding, then you can add runtime properties to types outside your control using TypeDescriptionProvider, which is a factory for an ICustomTypeDescriptor. You would then chain the original provider and create a custom PropertyDescriptor that obtained the additional data.

This is reasonably easy for read-only extra properties that are calculated based on the existing properties (and by "reasonably easy" I mean "only slightly insane"), but for read-write properties (or properties that are independent to the existing members) it is very hard, as you need to figure out where to put those values (in a way that still gets garbage collected etc). Non-trivial.

like image 39
Marc Gravell Avatar answered Jan 10 '23 11:01

Marc Gravell