Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a property without touching the class? (not inheritance)

I got a requirement in my project to add another property to some class. Now I want to avoid changing the class because I figured it shouldn't be aware that he has this property (this property only has significance in the context of this project).

The way I thought to accomplish this was (Please critic this because I wanna know if there are simpler ways of doing this)

  1. Adding a new singleton class that has a mapping between objects of my class and the type of the property I wanted to add
  2. adding in this class an extension method (extension property?) to access the mapping and fetch the property.

Is there a simpler alternative? Is this just unnecessary complexity? Maybe I should just add a new property to my class?

Thanks!

like image 278
PsyFish Avatar asked Feb 27 '23 13:02

PsyFish


2 Answers

The design you've described is actually the one used by Microsoft to implement the DependencyProperty system and, in particular, Attached Properties, though in the greater context of a binding framework. That said, using a dictionary with 'attached' data is a very typical solution when you need to tag a class with additional context for a particular use, but don't want to modify the class.

like image 175
Dan Bryant Avatar answered Apr 06 '23 14:04

Dan Bryant


Why do you say "not inheritance"? Surely the way to do this, if you don't want to alter the original class, would be to inherit from the original class and then add your property to the derived class?

BTW, there are only extension methods, not properties, so you can't do it via property.

like image 25
Dan Diplo Avatar answered Apr 06 '23 14:04

Dan Diplo