Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cast object with a Type variable

Tags:

The following doesn't work, of course. Is there a possible way, which is pretty similar like this?

Type newObjectType = typeof(MyClass);  var newObject = givenObject as newObjectType; 
like image 985
Michael Schnerring Avatar asked Jan 25 '12 15:01

Michael Schnerring


People also ask

Which is used for casting of object to a type or a class?

cast() method casts an object to the class or interface represented by this Class object.

How do you use type as variables?

For example: Type intType = typeof(Int32); object value1 = 1000.1; // Variable value2 is now an int with a value of 1000, the compiler // knows the exact type, it is safe to use and you will have autocomplete int value2 = Convert.

Can you type cast in TypeScript?

Type casting in TypeScript can be done with the 'as' keyword or the '<>' operator.

How do you typecast an object in TypeScript?

In TypeScript, you can use the as keyword or <> operator for type castings.


2 Answers

newObjectType is an instance of the Type class (containing metadata about the type) not the type itself.

This should work

var newObject = givenObject as MyClass; 

OR

var newObject = (MyClass) givenObject; 

Casting to an instance of a type really does not make sense since compile time has to know what the variable type should be while instance of a type is a runtime concept.

The only way var can work is that the type of the variable is known at compile-time.


UPDATE

Casting generally is a compile-time concept, i.e. you have to know the type at compile-time.

Type Conversion is a runtime concept.


UPDATE 2

If you need to make a call using a variable of the type and you do not know the type at compile time, you can use reflection: use Invoke method of the MethodInfo on the type instance.

object myString = "Ali"; Type type = myString.GetType(); MethodInfo methodInfo = type.GetMethods().Where(m=>m.Name == "ToUpper").First(); object invoked = methodInfo.Invoke(myString, null); Console.WriteLine(invoked); Console.ReadLine(); 
like image 182
Aliostad Avatar answered Sep 19 '22 19:09

Aliostad


You can check if the type is present with IsAssignableFrom

if(givenObject.GetType().IsAssignableFrom(newObjectType)) 

But you can't use var here because type isn't known at compile time.

like image 22
StuartLC Avatar answered Sep 20 '22 19:09

StuartLC