Rashim's Blog

How to make a reference type that behaves like a value type too?

Posted on: April 5, 2014

There is a special data type in .Net which is called string and it is a reference type, isn’t it? Of course it is but it also behaves much like a value type. That means it can directly accept values and does not require creating an instance. Have we ever thought for a single time how could we incorporate such a feature in our own class? Well, if we really need such type of feature we can easily implement it since operator overloading gives us the planetary for these purposes.

Operator overloading is a way to implement user-defined operator to be specified for operations where one or both of the operands are of a user-defined class or struct type. It also consents us to outline how the operators work with our class and struct. There are mainly three types of overload operators called unary, binary, and conversion. But not all operators of each type can be overloaded. According to MSDN, an implicit keyword is used to declare an implicit user-defined type conversion operator. In other words, this gives the power to our C# class, which can accept any reasonably convertible data type without type casting. And such a kind of class can also be assigned to any convertible object or variable.  By using this operator we can design our class which can take a value as well. Let’s move to the code.

public class StringManipulationHelper
{
private string _value;
private static StringManipulationHelper _stringManipulationHelper;

public StringManipulationHelper()
{
_value = string.Empty;
}

public StringManipulationHelper(string submittedValue)
{
_value = submittedValue;
}

public static implicit operator StringManipulationHelper(string submittedValue)
{
_stringManipulationHelper = new StringManipulationHelper(submittedValue);
return _stringManipulationHelper;
}

public static implicit operator string(StringManipulationHelper objHelper)
{
return objHelper._value;
}
}

Now you can use in any way like this,

StringManipulationHelper helper = null;
or
StringManipulationHelper helper = "This is test";
or
var helper = new StringManipulationHelper();
or
var helper = new StringManipulationHelper("This is a Test");

Easy enough right? But it will help us a lot when we are in need such kinds of features.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: