W
Wayne
Are user-defined conversions chosen at compile time, or are there ways to
make sure that they are chosen at run-time, based on the actual type of the
object?
Here is a simplified example of what I'm trying to accomplish:
I have a method that has a parameter of type object. If the parameter is a
boxed uint, it should unbox it. So, the method looks like this:
void f(object o)
{
uint u = (uint)o;
}
I don't have access to this method's source code, and can't change it.
Now, I would like to pass it other types of objects besides boxed uints, and
have it convert them to uints. For example, I've created the following
class:
class WrappedUInt
{
private uint m_wrappedUInt;
public WrappedUInt(uint u)
{
m_wrappedUInt = u;
}
public static explicit operator uint(WrappedUInt w)
{
return w.m_wrappedUInt;
}
}
If I try the following, the conversion is not invoked and I get a class cast
exception:
WrappedUInt wu = new WrappedUInt(37);
f(wu);
However, if f() is modified as followed:
void f(WrappedUInt o)
{
uint u = (uint)o;
}
the conversion is invoked and everything works fine.
This seems to imply that conversion operators are only selected at compile
time based on static type information, and don't make use of runtime type
information. Is there any way I can define a conversion that's based on the
actual type of the object at run time, so that the first version of f() will
work?
Thanks for any help you can provide.
Wayne
make sure that they are chosen at run-time, based on the actual type of the
object?
Here is a simplified example of what I'm trying to accomplish:
I have a method that has a parameter of type object. If the parameter is a
boxed uint, it should unbox it. So, the method looks like this:
void f(object o)
{
uint u = (uint)o;
}
I don't have access to this method's source code, and can't change it.
Now, I would like to pass it other types of objects besides boxed uints, and
have it convert them to uints. For example, I've created the following
class:
class WrappedUInt
{
private uint m_wrappedUInt;
public WrappedUInt(uint u)
{
m_wrappedUInt = u;
}
public static explicit operator uint(WrappedUInt w)
{
return w.m_wrappedUInt;
}
}
If I try the following, the conversion is not invoked and I get a class cast
exception:
WrappedUInt wu = new WrappedUInt(37);
f(wu);
However, if f() is modified as followed:
void f(WrappedUInt o)
{
uint u = (uint)o;
}
the conversion is invoked and everything works fine.
This seems to imply that conversion operators are only selected at compile
time based on static type information, and don't make use of runtime type
information. Is there any way I can define a conversion that's based on the
actual type of the object at run time, so that the first version of f() will
work?
Thanks for any help you can provide.
Wayne