I’m writing a class that holds a variable of any type. To do so, I store both the variable (as an object reference) and its Type. When I try to cast the object back to the correct type, though, I get error CS0118, because I’m using a field (which is of type Type) as a type.
Here is my class:
public class Node
{
Type m_oType = null;
public Type Type
{
get { return m_oType; }
set { m_oType = value; }
}
object m_oValue = null;
public object Value
{
get { return m_oValue; }
set
{
if (m_oValue == null)
{
if (value is m_oType) // ERROR CS0118
{
m_oValue = value;
}
}
}
}
}
I’ve tried to search online for a way to do this (i.e., using cast operators, as and is), but I keep getting the same basic tutorials about casting variables. Can someone give me a pointer as to how I can achieve this? Thanks.
I suspect you want something like this (but read on):
Note that we’re calling it on
m_oType, not passingm_oTypeto it. From the docs onIsAssignableFrom‘s return value, wherecis the parameter:For example,
typeof(object).IsAssignableFrom(typeof(string))returnstruebecauseobjectis in the inheritance hierarchy ofstring.EDIT: As noted, that will break if either
m_oTypeis null orvalueis null. We can get aroundvaluebeingnulleasily enough, but it’s not clear what you’d expect it to do ifm_oTypeis null. Perhaps you should prevent that in the setter for theTypeproperty (and the constructor)? Then use either: