Reputation: 1659
EDIT: Hopefully this helps, understand what I am trying to do.
I have a object returned which is of type Object, within this object I have a int value, based on this int value I want to be able to use a enum to tell me what specific object a should case this object to.
The Enum holds all possible casings.
I will receive a generic object (of type object) which can be one of many different more specific objects say in this case of type Model. I want to be able to look inside the object for an int value which will tell me which cast to use.
For instance a have objectA and it has a int value set to '2' within the object, I want to cast this object to my specific object based on my enum value 2, which is set to a specific type.
This may be very simple but cannot work out how you would so this and if it is possible, thank you.
Thanks.
Upvotes: 0
Views: 282
Reputation: 46947
It's a little hard to understand what you want. But this is my take on it. All your classes would need to implement interface ITypeContainer
to be able to extract the enum value.
void Main()
{
....
....
CastToType((ITypeContainer)myObject);
}
public void CastToType(ITypeContainer obj)
{
switch (obj.ObjectType)
{
case TypeEnum.Test1:
var o1 = (Test1)obj;
break;
case TypeEnum.Test2:
var o2 = (Test2)obj;
break;
}
}
public class Test1 : ITypeContainer
{
public TypeEnum ObjectType{ get; set; }
}
public class Test2 : ITypeContainer
{
public TypeEnum ObjectType{ get; set; }
}
public enum TypeEnum
{
Test1,
Test2,
Test3
}
public interface ITypeContainer
{
TypeEnum ObjectType{ get; set; }
}
Upvotes: 1
Reputation: 30708
Are you trying to typecast one enum to another?
Enum Type1
{
A
B
};
Enum Type2
{
A,
B
};
Type1 type1 = Type1.A;
if(Enum.IsDefined(typeof(Type2), type1.A.ToString())
{
Type2 type2 = (Type2)Enum.Parse(typeof(Type2), type1.A.ToString());
//type2 now holds Type2.A
}
EDIT
If you want to change type of an object at runtime, it is not possible.
If you just mean casting, (same object different representation corresponding to implemented interfaces, base class, etc), it is possible, but here object type does not change.
Upvotes: 2
Reputation: 1500903
If you mean you want to change the type of the objectA
variable at exection time, the answer is no. The compiler needs to know the type of the variable for all kinds of things which are done at compile time.
If you're using C# 4, you may be able to use dynamic
to help you - but it's not really clear what you're trying to achieve. In many cases it's a better idea to create a common interface which all of your types implement, and then just make the type of the variable the interface type. That's not universally applicable, but it's a good idea when it works.
Upvotes: 2