tags:

views:

199

answers:

3

I'm looking for a way to create a generic wrapper for any object.
The wrapper object will behave just like the class it wraps, but will be able to have more properties, variable, methods etc., for e.g. object counting, caching etc.

Say the wrapper class be called Wrapper, and the class to be wrapped be called Square and has the constructor Square(double edge_len) and the properties/methods EdgeLength and Area, I would like to use it as follows:

Wrapper<Square> mySquare = new Wrapper<Square>(2.5);  /* or */ new Square(2.5);
Console.Write("Edge {0} -> Area {1}", mySquare.EdgeLength, mySquare.Area);

Obviously I can create such a wrapper class for each class I want to wrap, but I'm looking for a general solution, i.e. Wrapper<T> which can handle both primitive and compound types (although in my current situation I would be happy with just wrapping my own classes).

Suggestions?

Thanks.

+3  A: 

Use Decorator pattern or write extension methods.

this. __curious_geek
Thanks. Decorator patterns are not suitable, I think, since they require me to change my entire program to use them, and I would like the wrapper to be transparent to the user of T. Regarding extension methods - can you use a similar method to add a variable to the class (i.e. to each object)? Or only methods?
Haggai
+1  A: 

Maybe something like this:

public class Wrapper<T>
{
    public readonly T Object;

    public Wrapper(T t)
    {
        Object = t;
    }
}

And then you could use it as follows:

Wrapper<Square> mySquare = new Wrapper<Square>(new Square(2.5));
Console.Write("Edge {0} -> Area {1}", mySquare.Object.EdgeLength, mySquare.Object.Area);
bender
Thanks, but that's what I'm trying to avoid. I would like the wrapper to be transparent to the user of T.
Haggai
+2  A: 

DynamicProxy from the Castle project might be the solution for you.

Brian Gideon
+1, yes - the question is clearly looking for a proxy implementation. DynamicProxy is widely used in the .NET open source world (NMock2, NHibernate, Ninject, etc. all use it). The only important caveat is that you won't be able to use a proxy for sealed classes.
Jeff Sternal
Thanks! This really looks like the solution I was looking for (although I'll have to dig more into it).
Haggai