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

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;
}
}
}
 
M

mikeb

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()
 
J

Jon Skeet [C# MVP]

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...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top