V
Vikas Manghani
Hi
I have an Enum say
publlic enum TestEnum
{
Val1 = 1,
Val2 = 2
}
In another class that uses a field of this Enum
public class TestClass
{
.....
public Nullable<TestEnum> enumValue;
]
In the client code, I want to assign this field a value from a generic
System.Object reference.
So
public class Client
{
public static void Main(String[] args)
{
object o = 2;
TestClass c1 = new TestClass();
c1.enumValue = (Nullable<TestEnum>)o;
//The above statement fails. But the following succeeds.
c1.enumValue = (TestEnum)o;
//Similarly
object o = null;
TestClass c2 = new TestClass();
c2.enumValue = (Nullable<TestEnum>)o;
//The above statement succeeds. But the following fails.
c3.enumValue = (TestEnum)o;
}
}
So basically, I have to test against null always before assigning a value.
Is there a way to achieve the type cast with a single statement?
Thanks in advance
Vikas
I have an Enum say
publlic enum TestEnum
{
Val1 = 1,
Val2 = 2
}
In another class that uses a field of this Enum
public class TestClass
{
.....
public Nullable<TestEnum> enumValue;
]
In the client code, I want to assign this field a value from a generic
System.Object reference.
So
public class Client
{
public static void Main(String[] args)
{
object o = 2;
TestClass c1 = new TestClass();
c1.enumValue = (Nullable<TestEnum>)o;
//The above statement fails. But the following succeeds.
c1.enumValue = (TestEnum)o;
//Similarly
object o = null;
TestClass c2 = new TestClass();
c2.enumValue = (Nullable<TestEnum>)o;
//The above statement succeeds. But the following fails.
c3.enumValue = (TestEnum)o;
}
}
So basically, I have to test against null always before assigning a value.
Is there a way to achieve the type cast with a single statement?
Thanks in advance
Vikas