views:

99

answers:

3

How can I convert a Decimal datatype to Object and still observe the IConvertable interface ToType() method. This is preliminary work in order to convert a custom datatype (based on Decimal) using Convert.ChangeType.

EDIT: we would like to convert to object so that we can support the ToType method of IConvertible. this method returns type object. the reason for this is for use in a method which populates a class objects properties based upon the property type.

+3  A: 

I don't think you can convert it to an object reference and keep the interface.

But you can cast it to an IConvertable reference and use that. That is just another form of boxing.

So the point is: why exactly do you want to cast it to an Object?

In addition, you can follow a route like this:

Decimal d = 10;
object x = d;

if (x is IConvertible) 
{ 
    string s = (x as IConvertible).ToString();
}
Henk Holterman
+2  A: 

Not sure why would you want to convert it to an object. If you want to use it as an IConvertable and maintain static type safety, just use IConvertable references. Once you cast to an object, the static type safety is lost.

However, an object never "looses" it's type information. If you must use object references, you can obtain a reference to an IConvertable by using the as keyword. It will return a valid reference if the cast succeeds and null, if the object doesn't implement the interface.

object num = new Decimal();
// ... 
IConvertable convertableNum = num as IConvertable;
if (convertableNum != null){
   // Do something meaningful ... 
}
ghostskunks
A: 

Like others, why you would want to convert is unclear, but everything in C# is an object by default at its topmost level. So, if you needed to pass it into a function / method for processing that was expecting an "object" data type, you could just typecast it, then re-convert it back to decimal if so needed..

CallYourFunction( (object)YourDecimalClass );

then, in your funciton

if( ParameterObject is YourDecimalClassType ) // do something...

DRapp