views:

284

answers:

5
+2  Q: 

dynamic casting?

I need a way to cast an object to a type that is not know at compiler time.

something like this:

object obj;

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

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

I doubt that something like this would be possible. Just checking to see if someone has a clever way of doing it.

+5  A: 

This is not possible in C# 3.0, but if you could define a common interface that all of your objects implement, you could cast to that.

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

Mark Seemann
Having battled such scenarios in several projects, I'd say having a common interface might be the best way to go.Accessing it's functionality depending on the type will go a bit more towards having a switch or some type of selector at some stage (so why not having type casting from the beginning?), after all, if it's unknown how are you gonna know what to access once casted?If this is part of some sort of plugin-like exec, using reflection and accessing its methods and properties thru that will remove the need of casting, hence loosely coupled.guess all this depends on what u need it for
samiq
+3  A: 

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.

Thorarin
+3  A: 

Well, you could do this with generics:

public class IAcceptValueTypes<T> where T: struct

private T obj;

public T Obj
{
    get { return obj; }
    set { obj = value; }
}

The generic constraint where T: struct will limit the acceptable type to value types.

Jon Limjap
+1  A: 

Hi, why do you need such kind of casting?

  1. If number of types is limited you can implement generic version of your property.
  2. You can use the reflection to understand type of passed object and cast to this type.
G2
+1  A: 

I don't currently have Visual Studio in front of me to try out, but why don't you look up:

  • GetType
  • Convert.ChangeType
Hai Vu