Wrapper Patterns in C#: Part I

Did you ever wish for a superhuman power to be impervious to bullets or travel outside your body? How about the superpower to be able to breathe underwater? Or how about a changing the way you look so you can disguise yourself as anyone, or anything? In this series of four articles, we will travel down the C# wrapper rabbit hole and see how it is all possible with some patterns: Proxy, Decorator, and Adapter.

Creating a Basic Wrapper.

These three patterns, proxy, decorator, and adapter are all implemented identically. They are all wrappers at the basic level. The functionality they provide is how we can make the distinction between them. Let's first look at a template for a basic wrapper and then at how to use a wrapper to implement each of these patterns can help us in our quest for the bizarre.

Before we begin to understand how to perform super-feats, we need to understand the basic super-power all C# developers are born with - our secret ability to wrap (not to be confused with rap). Here is how a wrapper works:

Let's say we have a Thing with a ThingString property and a method PrintThingString() as below:

class Thing

{

privatestring m_string;

publicstring ThingString

{

get { return m_string; }

set { m_string = value; }

}

publicvoid PrintThingString()

{

Console.WriteLine(m_string);

}

}

Here is how we create a basic ThingWrapper to wrap the Thing. It contains a reference to the Thing being wrapped and has the same signature. The ThingWrapper just passes requests into the wrapped Thing.

class ThingWrapper

{

private Thing m_thing;

public ThingWrapper(Thing pThing)

{

m_thing = pThing;

}

publicstring ThingString

{

get { return m_thing.ThingString; }

set { m_thing.ThingString = value; }

}

publicvoid PrintThingString()

{

m_thing.PrintThingString();

}

}

Because the ThingWrapper has the same signature as the Thing, it is really no different dealing with the Thing or the ThingWrapper. We can work with either the Thing or the ThingWrapper access our internal string m_string, or perform the base functionality which is to print a line to the console.

Thing t = new Thing();

t.ThingString = "This is the ThingString";

t.PrintThingString();

ThingWrapper tWrap = new ThingWrapper(t);

tWrap.PrintThingString();

tWrap.ThingString = "This is still the ThingString";tWrap.PrintThingString();

We can wrap any class this way. Now that we understand this "wrapping power", we should only use it for good (or to do some cool stuff). Just remember, things can get pretty complicated if we have wrappers that are really not needed. Sometimes, however, we just can't live without them. Starting in the next article, let's next look at some of the super powers we can manifest using wrappers.