Dynamic casting?

I need a way to pass an object to a type that is unknown at compile time.

something like that:

object obj; public (type of obj) Obj { get { return obj } set { obj = (type of obj)value; } } 

The only thing known is that obj is a value type.

I doubt something like this will work out. Just check if anyone has a smart way to do this.

+3
source share
5 answers

This is not possible in C # 3.0, but if you could define a common interface that implements all your objects, you can use it.

In C # 4.0, we get the dynamic keyword that allows us to do Duck Typing.

+6
source

Such an actor didn’t actually do anything, because you are assigning back a variable with more free typing. Your best approach depends on what you want to do with the value type after casting.

Options:

  • Reflection
  • C # 4.0 dynamic .
  • A simple switch or if .. else based on the type of the variable.

Edit: using a generic class doesn't actually solve your problem if you don't know anything about the type at compile time, but your example does not illustrate the actual use of your class, so it may be that I misinterpret your intentions. Maybe something similar to what you are 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 typical type parameter. Strictly speaking, the type is still static because it is known at compile time.

+4
source

Well, you can do this with generics:

 public class IAcceptValueTypes<T> where T: struct private T obj; public T Obj { get { return obj; } set { obj = value; } } 

The general restriction is where T: struct limit the allowed type to the value of types.

+4
source

why do you need such a casting?

  • If the number of types is limited, you can implement a generic version of your property.
  • You can use reflection to understand the type of object passed and apply it to that type.
+1
source

I currently don't have Visual Studio to try, but why don't you take a look:

  • Gettype
  • Convert.ChangeType
+1
source

All Articles