0

Referring the code below:

Void Work(object obj,Type objType)
{
   //code to downcast obj to type speciied in objType
}

I am new to Reflections in C#. I'll really appreciate if someone can guide me how can I downcast obj to the type specified in objType. Is is possible, or my approach is wrong?

Refering to Casting a variable using a Type variable,

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

could be a possible solution, but how do I pass the Type in objType variable to ?

Community
  • 1
  • 1
Amit Mittal
  • 1,129
  • 11
  • 30
  • 1
    What is your motivation for writing code this way, instead of using [generics](http://msdn.microsoft.com/en-us/library/512aeb7t.aspx) to let the compiler do the heavy lifting for you? – Cody Gray - on strike Apr 23 '13 at 04:32
  • 1
    See this: http://stackoverflow.com/questions/972636/casting-a-variable-using-a-type-variable – Habib Apr 23 '13 at 04:34
  • As a template type parameter: `CastExample(myObject);` The links you've been given already explain this. – Cody Gray - on strike Apr 23 '13 at 04:45
  • 2
    You can't get the compile-time type if you're given the type at runtime... – Jeff Mercado Apr 23 '13 at 04:47
  • 2
    When you're working with reflection and `object` types, there is no need to cast anything. Casting is useful when you are relying on strong types, and it is used for compile-time type verification. – Mohammad Dehghan Apr 23 '13 at 04:58
  • @JeffMercado: I wouldn't say can't... He could use generics and use `MakeGenericMethod()` at runtime. – Elad Lachmi Apr 23 '13 at 04:58
  • 1
    @Elad: What good would that do? Sure you can make an _instance_ of an object, method, generic whatever of a given type, but that still won't give it to you at compile time. – Jeff Mercado Apr 23 '13 at 05:06
  • @JeffMercado: True, but from the question it seems like the method/class does not know the type at compile time. My point was that he could use generics even if he does not generate the strong-typed method at compile time. – Elad Lachmi Apr 23 '13 at 05:26
  • 1
    Casting, especially downcasting, is for strong-typing as @MD.Unicorn said. OP's approach does not make any sense to me. Convert.ChangeType would convert, e.g. int to string, but it's not actually casting. I think OP should declare the usage of the method. – tia Apr 23 '13 at 05:27
  • 1
    Thanks folks! I've solved my problem. I've changed my approach so that there is no more any need of typecasting or generics. Thanks for your effort anyways. – Amit Mittal Apr 23 '13 at 05:39

0 Answers0