Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamically decorating objects in c#

Tags:

c#

decorator

is it possible to easily and dynamically decorate an object?

for example, lets say I have a List<PointF>. this list is actually a plot of the sine function. I'd like to go through these points and add a flag to each PointF of whether it's a peak or not.

but I don't want to create a new extended SpecialPointF or whatever, that has a boolean property.

judge me all you want for being lazy, but laziness is how awesome ideas are born (also bad ideas)

Edit: I'll accept boxing solutions as well as any interesting hack you can come up with. there's nothing really stopping me from deriving. I just want to know if there's a more fun way.

like image 783
Oren Mazor Avatar asked Apr 29 '10 16:04

Oren Mazor


1 Answers

No, there's no way to do (specifically) what you're asking for.

Assuming you're using C# 3.0+, you can use anonymous types to do this, assuming that you don't want to expose the information outside of your function.

var decoratedList = sourceList.Select(pt => new 
                    { 
                        IsPeak = GetIsPeak(pt), 
                        Point = pt 
                    }).ToList();

This will give you a new List<T> object. This may very well not solve your problem, since you cannot extend this outside of a single function call and you're creating a new list rather than modifying an existing one, but hopefully this helps.

like image 143
Adam Robinson Avatar answered Oct 23 '22 21:10

Adam Robinson