Such a cast would not actually do anything, because you're assigning at back to a variable with looser typing. Your best approach depends on what you want to do with the value type after "casting" it.
Options are:
- Reflection
- C# 4.0
dynamic
typing.
- A simple
switch
or if .. else
based on the variable type.
Edit: using a generic class does not actually solve your problem if you know nothing about the type at compile time, but your example does not illustrate the actual usage of your class, so it may be that I'm misinterpreting your intentions. Something like this might actually be what you're looking for:
class MyClass<T> where T: struct
{
T obj;
public T Obj
{
get { return obj; }
set { obj = value; }
}
}
MyClass<int> test = new MyClass<int>();
test.Obj = 1;
The actual type definition is now outside your class, as a generic type parameter. Strictly speaking, the type is still static in that it is known at compile time however.