cast object with a Type variable

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.


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();

Tags:

C#

Types