Friday, January 16, 2009

Using Custom Type with Conversion Operator

Using Custom Type with Conversion Operator

So, let’s start, Today I will discuss how you can decorate your custom Type to make it usable.

Step 1: Creating Custom Type with Conversion Operators

I will create my custom type “PercentageInteger”, this is a integer with special purpose as it can only have a value between 0-100.

struct PercentageInteger

{

public int percentage;

public static implicit operator PercentageInteger(int arg)

{

PercentageInteger pi = new PercentageInteger();

if (arg <>

pi.percentage = 0;

else if (arg > 100)

pi.percentage = 100;

else

pi.percentage = arg;

return pi;

}

public static explicit operator int(PercentageInteger arg)

{

return arg.percentage;

}

public static explicit operator bool(PercentageInteger arg)

{

return true;

}

}

Step 2: Explaning Convertion Operator

public static implicit operator PercentageInteger(int arg)

Obove line tells C# compiler that this “PercentageInteger” type can accept “int” as its value.

So we can use this Type as follows..

PercentageInteger per = 100;

public static explicit operator int(PercentageInteger arg)

Obove line tells C# compiler that “PercentageInteger” type can be Cast to Type “int”.

So we can use this Type as follows..

PercentageInteger per = 100;

int x = (int)per;

bool y = (bool)per;

No comments: