how to cast an object to the type stored in a System.Type variable?

  • Thread starter Thread starter Fred Zolar
  • Start date Start date
F

Fred Zolar

Anyone know how to cast an object to the type stored in a System.Type
variable? I need to cast m_oValue to an int, bool, ect... based on the
variable Type.


public class TestClass
{
private object m_oValue;
public System.Type Type;

public object Value
{
get { return m_oValue; }
set
{
if (Type2 == null) m_oValue = value;
else
{
// the line below doesn't work
// trying to cast value to this.Type
// m_oValue = (typeof(this.Type)) value;
}
}
}
 
Fred said:
Anyone know how to cast an object to the type stored in a System.Type
variable? I need to cast m_oValue to an int, bool, ect... based on the
variable Type.


public class TestClass
{
private object m_oValue;
public System.Type Type;

public object Value
{
get { return m_oValue; }
set
{
if (Type2 == null) m_oValue = value;
else
{
// the line below doesn't work
// trying to cast value to this.Type
// m_oValue = (typeof(this.Type)) value;
}
}
}

I think you want System.Convert.ChangeType()
 
Fred Zolar said:
Anyone know how to cast an object to the type stored in a System.Type
variable? I need to cast m_oValue to an int, bool, ect... based on the
variable Type.


public class TestClass
{
private object m_oValue;
public System.Type Type;

public object Value
{
get { return m_oValue; }
set
{
if (Type2 == null) m_oValue = value;
else
{
// the line below doesn't work
// trying to cast value to this.Type
// m_oValue = (typeof(this.Type)) value;
}
}
}

You can't cast dynamically - but why do you want to? m_oValue is always
going to be of type object, so what do you expect the cast to do? If
you want to convert ints to bytes or something like that, you could use
Convert.ChangeType, I suppose...
 
Back
Top