Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# wrapper for objects

Tags:

c#

wrapper

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.

like image 566
Haggai Avatar asked May 28 '10 09:05

Haggai


2 Answers

Use Decorator pattern or write extension methods.

like image 94
this. __curious_geek Avatar answered Sep 28 '22 03:09

this. __curious_geek


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

like image 32
Brian Gideon Avatar answered Sep 28 '22 02:09

Brian Gideon