views:

1395

answers:

4

In C# can I cast a variable of type object to a variable of type T where T is defined in a Type variable?

+3  A: 

Putting boxing and unboxing aside for simplicity, there's no specific runtime action involved in casting along the inheritance hierarchy. It's mostly a compile time thing. Essentially, a cast tells the compiler to treat the value of the variable as another type.

What you could do after the cast? You don't know the type, so you wouldn't be able to call any methods on it. There wouldn't be any special thing you could do. Specifically, it can be useful only if you know the possible types at compile time, cast it manually and handle each case separately with if statements:

if (type == typeof(int)) {
    int x = (int)obj;
    DoSomethingWithInt(x);
} else if (type == typeof(string)) {
    string s = (string)obj;
    DoSomethingWithString(s);
} // ...
Mehrdad Afshari
Could you please explain that clearer in relation to my question?
theringostarrs
What I'm trying to explain is, what you would be able to do after that? You can't do much as the C# compiler requires static typing to be able to do a useful thing with the object
Mehrdad Afshari
You're right. I know the expected types of two variable which are sent to the method as type 'object'. I want to cast to expected types stored in variables, and add them to collection. Much easier to branch on type and attempt a normal cast and catch errors.
theringostarrs
Your answer is good, but just to be nit-picky, I note that casts never affect _variables_. It is never legal to cast a _variable_ to a variable of another type; variable types are invariant in C#. You can only cast the _value_ stored in the variable to another type.
Eric Lippert
+1  A: 

How could you do that? You need a variable or field of type T where you can store the object after the cast, but how can you have such a variable or field if you know T only at runtime? So, no, it's not possible.

Type type = GetSomeType();
Object @object = GetSomeObject();

??? xyz = @object.CastTo(type); // How would you declare the variable?

xyz.??? // What methods, properties, or fields are valid here?
Daniel Brückner
If youre using a generic class, that defines a method with return value of type T, you could need to do that. E.g. parsing a string to an instance of T and returning that.
BeowulfOF
A: 

Sure you can here is both a simple (assume this is a T-type cast) cast and if convenient a (assume we can convert this to a T) convert:

public T CastExamp1<T>(object input) {   
    return (T) input;   
}

public T ConvertExamp1<T>(object input) {
    return (T) Convert.ChangeType(input, typeof(T));
}
Zyphrax
How do you do this, my c# compiler complains about "return (T) input".
BeowulfOF
The ConvertExamp1 worked awesome for me. Thanks Zyphrax!
Jordan S